Skip to content

Add asynchronous query-slot admission for refreshable materialized views - #112808

Open
vanchaklar wants to merge 20 commits into
ClickHouse:masterfrom
vanchaklar:agent/refreshable-mv-workload
Open

vanchaklar wants to merge 20 commits into
ClickHouse:masterfrom
vanchaklar:agent/refreshable-mv-workload

Conversation

@vanchaklar

@vanchaklar vanchaklar commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #85741
Related: #101902
Related: #118419

Depends on #118419 for independent metadata statement scheduling. That dependency's commits and implementation are not included in this PR; this PR continues to target master. Refresh admission and execution use the normal workload setting from the stored SELECT, with no separate refresh workload setting. Until the dependency lands, CREATE still participates in the stored SELECT workload and can wait for its resources; replicated creation with a one-slot workload can also self-block. The dependency provides the separate metadata_workload behavior. This PR does not claim to fix metadata/runtime isolation by itself.

The default-off server setting use_query_slot_to_refresh_materialized_view makes refreshes participate in workload query-slot and initial memory-reservation admission. A refresh queues asynchronously for a configured QUERY resource and reports WaitingForResource without occupying a background execution worker. Initial memory reservations also apply when configured with reserve_memory, including workloads without a QUERY resource. workload_admission_timeout_ms bounds the combined admission wait.

IQuerySlot separates slot ownership from admission. The synchronous QuerySlot keeps its existing behavior, RefreshTask owns asynchronous admission, and ProcessList adopts the granted slot. STOP, PAUSE, drop and shutdown cancel pending admission and release coordination state. Execution rebuilds the context and SELECT from current metadata after admission; a changed workload requires a new admission attempt. Query-aware schedulers receive the classifier-owned scheduling context through ResourceLink::enqueue.

Integration coverage includes default-off compatibility, queued and immediate admission, query-aware scheduling and priority ordering, no QUERY resource, timeout and memory-admission cancellation, stop/pause/drop races, metadata changes while queued, replicated cleanup. Test setup creates views before installing constrained resources where existing metadata admission would otherwise block setup; the refresh-time limits and assertions are unchanged. Metadata/runtime-isolation integration cases are kept separately for validation with the dependency and are not in this PR. The starvation regression uses five background workers, ten long refreshes sharing one slot, and 100 views refreshing every second; it checks each fast view through a slow-refresh slot handoff. Local Python/XML, source and history checks passed. C++ builds and integration execution remain for CI; no runtime pass is claimed.

Changelog category (leave one):

  • Improvement

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

Added the default-off server setting use_query_slot_to_refresh_materialized_view so refreshable materialized views can participate in workload admission using their stored SELECT's workload. Refreshes wait asynchronously for query slots, reporting WaitingForResource without occupying a background execution worker, and pending query-slot or initial memory-reservation admission can be cancelled.


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

@vanchaklar
vanchaklar marked this pull request as ready for review July 31, 2026 22:29
@vanchaklar
vanchaklar requested a review from a team as a code owner July 31, 2026 22:29

Copy link
Copy Markdown
Contributor Author

@serxa, could you take a look at this when you have a chance? This touches the workload query-slot path and the boundary between the resource scheduler and BackgroundSchedulePool, so your feedback would be especially useful.

The main design point is that an RMV with REFRESH ... SETTINGS workload = ... requests QUERY admission asynchronously, reports WaitingForResource while queued, and does not occupy a RefreshExec background worker. Once admitted, the pre-acquired query slot is transferred into ProcessList for the refresh. Pending admission is cancellable on STOP/drop/shutdown.

I'd particularly appreciate your thoughts on whether the asynchronous QuerySlot admission/cancellation interface is the right abstraction here.

Copy link
Copy Markdown
Contributor Author

Friendly follow-up, @serxa. Since the previous ping, I tightened the scheduler boundary:

  • exceptions from the asynchronous query-slot callback no longer escape the resource-scheduler thread;
  • a failed immediate RefreshExec dispatch retries through the delayed background queue;
  • QuerySlot::wait() now waits for callback completion;
  • the docs and tests cover workloads with no configured QUERY resource.

The PR is mergeable, but CI has not started and there has not been a review yet. Could you confirm whether asynchronous QuerySlot admission plus transfer of the pre-acquired slot into ProcessList is the right direction, or point me to the preferred reviewer for this area?

Copy link
Copy Markdown
Contributor Author

@al13n321, could you also review the refreshable-MV side of this change? You authored the RMV implementation and have maintained RefreshTask, so your feedback on the lifecycle and cancellation semantics would be especially helpful.

The scheduler-side question is already with @serxa. On the RMV side, the key behavior is that workload belongs to REFRESH ... SETTINGS; a refresh waiting for admission reports WaitingForResource, does not occupy a RefreshExec worker, transfers the granted query slot into ProcessList, and cancels pending admission on STOP, drop, and shutdown.

The PR is mergeable, but has not received CI or a formal review yet.

@al13n321 al13n321 left a comment •

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 RMV part looks very sloppy but probably correct, I'm ok with it.

@al13n321

Copy link
Copy Markdown
Contributor

Why not take workload from the SELECT's settings? It seems like a landmine otherwise: I expect that many users would do CREATE MATERIALIZED VIEW ... AS SELECT ... SETTINGS workload = 'foo' and be surprised when the setting is ignored, then be annoyed to learn that they're supposed to move it to some weird random other part of the query. StorageMaterializedView::prepareRefresh applies settings from SELECT to refresh_context; maybe that part of prepareRefresh can be moved to happen before reading execution.workload in doScheduling, so that doScheduling can take the setting from the context?

vanchaklar commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@al13n321, good question. I placed workload in REFRESH ... SETTINGS intentionally.

The refresh-level workload applies to the complete refresh:

  • scheduler admission;
  • internal refresh operations;
  • the RMV SELECT query.

If both settings are present, the refresh-level workload takes precedence:

REFRESH ... SETTINGS workload = 'refresh_workload'
AS SELECT ...
SETTINGS workload = 'select_workload'

In this case, the complete refresh uses refresh_workload.

If no refresh-level workload is specified, the SELECT-level workload keeps its existing behavior. It applies to refresh execution, but it does not enable admission before RefreshExec starts.

Keeping the setting at the refresh level also allows users to move an RMV to another workload with ALTER ... MODIFY REFRESH. They do not need to modify or revalidate the SELECT query.

There are a few possible designs:

  1. Use the refresh-level workload for the complete refresh, as this PR does. This provides one workload for admission and execution.

  2. Take the workload only from the SELECT settings. This is simpler, but changing the workload requires modifying the SELECT. It could also make existing RMVs start waiting for QUERY admission after an upgrade.

  3. Use the refresh-level workload only for admission and keep the SELECT-level workload for execution. This provides more control, but one refresh would use different workloads at different stages and the behavior would be harder to understand.

  4. Use the refresh-level workload when present and otherwise use the SELECT workload for admission. This is convenient, but it would also change the scheduling behavior of existing RMVs.

I chose the first option because it is explicit, consistent, and easy to change operationally. I agree that the scope and precedence should be documented clearly.

@Blargian
Blargian removed the request for review from a team August 19, 2026 09:51

Copy link
Copy Markdown
Contributor Author

@al13n321, a quick follow-up: I addressed your state-check comments, clarified the refresh-vs-SELECT workload semantics, expanded the related tests, and synced the branch with current master. The PR is mergeable now. When you have a chance, could you take another look and let me know if the RMV side is in better shape?

@vanchaklar
vanchaklar requested a review from al13n321 August 24, 2026 06:24
Comment thread src/Interpreters/ProcessList.cpp Resolved
@al13n321

al13n321 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

@serxa , can you please review the scheduling part (ProcessList, QuerySlot)?

@al13n321 al13n321 added the can be tested Allows running workflows for external contributors label Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ebfd81]

Summary: ❌

job_name test_name status info comment
Code Review FAIL
Integration tests (amd_asan_ubsan, db disk, targeted) FAIL
test_refreshable_mv_query_slots/test.py::test_pending_memory_reservation_can_be_cancelled[STOP] FAIL cidb
test_refreshable_mv_query_slots/test.py::test_pending_memory_reservation_can_be_cancelled[PAUSE] FAIL cidb
test_refreshable_mv_query_slots/test.py::test_pending_memory_reservation_can_be_cancelled[DROP] FAIL cidb
test_refreshable_mv_query_slots/test.py::test_async_admission_preserves_query_priority FAIL cidb
Integration tests (amd_asan_ubsan, flaky) FAIL
test_refreshable_mv_query_slots/test.py::test_pending_memory_reservation_can_be_cancelled[STOP] FAIL cidb
test_refreshable_mv_query_slots/test.py::test_pending_memory_reservation_can_be_cancelled[PAUSE] FAIL cidb
test_refreshable_mv_query_slots/test.py::test_pending_memory_reservation_can_be_cancelled[DROP] FAIL cidb
test_refreshable_mv_query_slots/test.py::test_async_admission_preserves_query_priority FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (amd_illumos) DROPPED
Build (ppc64le) DROPPED

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

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 1ebfd81854bfcdeb7c3ad7ab321a64bb342b949b was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@serxa serxa 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.

I like the idea, thanks! A few things before it's mergeable:

  1. Don't use a separate refresh-level workload - take one from SELECT. Admission should use the workload that the refresh runs under. The same way memory reservations already do: admission is based on the same workload. Two workload knobs is an ambiguity we'd carry forever. Refreshes now competing for query slots is backward-incompatible, so gate it behind a server setting use_query_slot_to_refresh_materialized_view (default off, we flip on later once query slots are common). This mirrors the way, e.g., cpu_slot_preemption handled its transition. Server settings can be easily depreciated later, and SQL syntax is almost impossible to change.

  2. Split QuerySlot's two roles. It currently both holds a granted slot (its real job) and talks to the scheduler. Introduce IQuerySlot (with using QuerySlotPtr = std::unique_ptr<IQuerySlot>), keep the existing synchronous QuerySlot as-is, and make the async variant an inner class of RefreshTask wired directly to the task's own state; shared bits (metrics) can sit in a QuerySlotBase. That lets you drop the std::function the scheduler thread currently runs. ResourceRequest::execute() is meant to be fast, and arbitrary callbacks don't belong on that thread.

  3. ProcessList::insert shouldn't call wait(). A slot handed to insert should already be granted. Insert's only job is to adopt it and tie its lifetime to the QueryStatus. Do the waiting (really, the grant/failure resolution) in the refresh path: with the async slot, RefreshExec is dispatched only once the slot is granted, so by the time we reach insert the outcome is known, and a failed or cancelled admission errors out before insert is ever called. That also lets force_query_slot go away. It exists only to force insert to acquire a slot for an otherwise-unlimited internal query, but if the refresh pre-acquires and passes an already-granted slot, insert can simply adopt whatever slot it's given and the flag is unnecessary.

  4. Handle WaitingForResource on shutdown. The is_shutdown paths still only normalize Requested. A refresh cancelled while queued for a slot can leave refresh_running / the /running znode uncleared until the Keeper session expires, so other replicas keep treating it as in flight. The failing ..._wait_can_be_stopped test looks like exactly this.

  5. Put the docs in ParserCreateQuery.cpp. The view.mdx change is inside an autogenerated block.

@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
Follow the scheduler review: add default-off `use_query_slot_to_refresh_materialized_view`, separate `IQuerySlot` ownership from synchronous admission, and keep asynchronous admission inside `RefreshTask`. Adopt granted slots in `ProcessList` without waiting or a force flag.

Preserve current master shutdown fixes, normalize queued refreshes on shutdown, rebuild execution context from current metadata after admission, and retain the old design on `agent/refreshable-mv-workload-refresh-setting-checkpoint`.

Move generated view documentation to `ParserCreateQuery.cpp` and add integration coverage for compatibility, admission, cancellation, failure, definition changes and Keeper cleanup. Use CI for ClickHouse build and integration validation.

Related: ClickHouse#112808
Review: ClickHouse#112808 (review)
@vanchaklar vanchaklar changed the title Add workload setting for refreshable materialized views Add asynchronous query-slot admission for refreshable materialized views Sep 5, 2026
Release a granted slot when `STOP` or `PAUSE` interrupts a refresh before
execution starts. Release the refresh query slot before table exchange
and error cleanup. Add failpoint coverage for both lifetime boundaries.

Record `runtime_workload` in the settings history to unblock the fast test.

Related: ClickHouse#112808
Use the refresh-specific name in the setting, implementation, history,
documentation, and integration tests. Behavior and defaults are unchanged.
Comment thread src/Interpreters/ProcessList.cpp Resolved
Resolve the `SettingsChangesHistory.cpp` overlap by preserving `refresh_workload` and the new join-order settings.

Related: ClickHouse#112808
@serxa

serxa commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

So the question is whether DDL and runtime execution should share the same workload limits. I added refresh_workload to explore separating these policies. How would you approach this within the scheduler’s design?

Yep, the workload for DDL is not addressed yet at all, you are right. I think this should be a separate, wider topic. We will have a new ddl_workload query setting, which will be "injected" into the context instead of workload for DDL queries. And we should just disable using resources from any workload for DDL query by default. This not what people wanted. Workloads are intended for normal queries, but if you need it for DDL for some reason, we will use that new setting. Working on it here. #118419

@vanchaklar

Copy link
Copy Markdown
Contributor Author

@serxa
You guys are the best!

@CLAassistant

CLAassistant commented Sep 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Sep 15, 2026
Comment thread src/Interpreters/ProcessList.cpp Resolved
Comment thread src/Core/ServerSettings.cpp Outdated
- [Workload Scheduling](/concepts/features/configuration/server-config/workload-scheduling)
)", 0) \
DECLARE(Bool, use_query_slot_to_refresh_materialized_view, false, R"(
When enabled, refreshable materialized views request a query slot before starting refresh execution. The stored SELECT setting `refresh_workload` selects the refresh workload; when empty, the existing `workload` setting is used. This requires a configured QUERY resource for that workload. While queued, the refresh reports `WaitingForResource` in `system.view_refreshes` without occupying a background execution worker.

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 contract in this doc string is too narrow now. Enabling use_query_slot_to_refresh_materialized_view does not only matter when the workload has a QUERY resource: ProcessList::insert now forces internal RMV refreshes through workload resources in general, so they also wait/fail on a workload MEMORY RESERVATION resource when reserve_memory is set, even if there is no QUERY resource at all. test_refresh_uses_memory_reservation_resource covers exactly that shape.

As written, this tells operators the setting has no effect unless they configure QUERY, but the current code changes refresh behavior for memory-limited workloads too. Please document the broader contract here and then describe the QUERY-slot part as the async pre-start wait.

@al13n321 al13n321 removed the can be tested Allows running workflows for external contributors label Sep 17, 2026
@al13n321

Copy link
Copy Markdown
Contributor

Watch your bot.

@vanchaklar

Copy link
Copy Markdown
Contributor Author

**al13n321 **

restrictions applied for the bot.

Consolidate the later compatibility, query-slot deadline, cancellation,
initial memory-reservation and shutdown fixes without temporary helper
workflows. Keep the earlier implementation history through debb128.

Preserve Alexey Milovidov's merge-resolution contributions from
3a4eab9 and
b336418. The original history remains at
backup/pr112808-before-cleanup-20261011-b3364185.

Related: ClickHouse#112808

Co-authored-by: Alexey Milovidov <[email protected]>
@vanchaklar
vanchaklar force-pushed the agent/refreshable-mv-workload branch from b336418 to ffebb9f Compare October 11, 2026 10:41
vanchaklar added a commit to vanchaklar/ClickHouse that referenced this pull request Oct 11, 2026
Use the normal stored `SELECT` setting `workload` for refresh admission
and execution. Remove `refresh_workload` and nested setting rewrites;
metadata statements follow `metadata_workload` and `use_metadata_workload`.

Use `ResourceLink::enqueue` so asynchronous admission carries the query's
scheduling context. Cover fair, LAS and priority scheduling, plus append
and replacement refreshes in Atomic and Replicated databases with metadata
scheduling enabled and disabled. Preserve timeout, cancellation, memory
admission and bounded-pool starvation coverage.

Clarify the initial memory-reservation contract and move the system-table
description into structured documentation instead of generated output.

Related: ClickHouse#112808
Related: ClickHouse#118419
…scheduling

Remove `refresh_workload` and nested query rewriting. Keep asynchronous
admission on the stored `SELECT` workload, with classifier-aware enqueue,
query-aware scheduler coverage, cancellation, and the starvation regression.

Keep metadata scheduling implementation and its integration-only test matrix
out of this branch. It is a separate dependency:
ClickHouse#118419

Create test views before installing constrained resources where existing
metadata admission would otherwise block setup. Runtime slot limits, memory
limits, cancellation assertions, and starvation invariants are unchanged.

This corrects dependency inclusion in:
ClickHouse#112808

Validation: Python syntax, XML parsing, source and graph checks. C++ builds
and integration execution require CI; no runtime pass is claimed.
@vanchaklar
vanchaklar force-pushed the agent/refreshable-mv-workload branch from ffebb9f to b237d36 Compare October 11, 2026 11:00
@vdimir
vdimir requested a review from serxa October 15, 2026 08:03
@vanchaklar
vanchaklar force-pushed the agent/refreshable-mv-workload branch from 4ca519d to 1ebfd81 Compare November 1, 2026 11:04
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 14, 2026

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

can be tested Allows running workflows for external contributors comp-refreshable-materialized-view Refreshable materialized views: scheduled/periodic refresh, refresh state machine, refresh orches... external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add execution pool for Refreshable Materialized Views

6 participants