Skip to content

Add unified SYSTEM STOP/PAUSE/CANCEL/REFRESH for streaming engines and materialized views - #107476

Merged
nikitamikhaylov merged 103 commits into
ClickHouse:masterfrom
NIKTONIKTO717:system-stop-pause-cancel-refresh
Jul 21, 2026
Merged

nikitamikhaylov merged 103 commits into
ClickHouse:masterfrom
NIKTONIKTO717:system-stop-pause-cancel-refresh

Conversation

@NIKTONIKTO717

@NIKTONIKTO717 NIKTONIKTO717 commented Jun 15, 2026 •

Copy link
Copy Markdown
Member

Closes: #102707
Closes: #108104

One unified set of SYSTEM commands to control the background activity of the streaming engines (Kafka, RabbitMQ, NATS, S3Queue/AzureQueue) and refreshable materialized views (RMV). Previously RMV had its own SYSTEM ... VIEW commands and the streaming engines had no per-table SQL control.

SYSTEM STOP    [db.]table | ALL BACKGROUND   -- abort the in-flight read AND block further cycles
SYSTEM START   [db.]table | ALL BACKGROUND   -- resume (undo STOP / PAUSE)
SYSTEM PAUSE   [db.]table | ALL BACKGROUND   -- block further cycles, let the running one finish
SYSTEM CANCEL  [db.]table | ALL BACKGROUND   -- abort the in-flight read only, keep scheduling
SYSTEM REFRESH [db.]table | ALL BACKGROUND   -- run exactly one out-of-order cycle

On an RMV the verbs are aliases of the existing SYSTEM ... VIEW commands. ALL BACKGROUND applies the verb to every such table at once.

How the verbs behave

A cycle = read a block → insert into the dependent MVs → reach the engine's commit point. Each verb has 2 effects:

verb block future cycles? abort in-flight cycle? note
STOP yes yes = PAUSE + CANCEL
PAUSE yes no running cycle still commits
CANCEL no yes keeps scheduling
START unblock — undo STOP / PAUSE
REFRESH — — one extra out-of-order cycle

The abort is best-effort: STOP/CANCEL are honored only while the source is still reading the block. Once the insert has started, the block runs to its commit point (mid-insert it acts like PAUSE), aborting it then would duplicate the already-inserted rows. S3Queue/AzureQueue are the exception: their source streams files straight into the insert (one fused pipeline, no buffered block to drop), so the abort cancels the pipeline. Files in progress are reprocessed, files already done stay done. Aborted data is redelivered later. Core NATS has no replay and drops it.

Engine Commit point What STOP/CANCEL abort
Kafka v1/v2 offset commit the read (a running insert still commits)
RabbitMQ AMQP ack the read (a running insert still acks)
NATS (JetStream) JetStream ack the read (a running insert still acks)
NATS (core) none (at-most-once) the in-flight read, but it is lost (no replay)
S3Queue / AzureQueue file marked Processed the read and the insert (files reprocessed)*
RMV refresh committed the in-progress refresh

* With deduplication off (non-default), the in-flight batch finishes and commits instead.

REFRESH runs immediately on a streaming table (even while stopped, then re-blocks). On a stopped RMV it defers until START, like SYSTEM REFRESH VIEW.

Design notes

  • AST: scope lives in the Type enum (5 basic verbs + 5 *_ALL_BACKGROUND). Basic verbs match in a fallback after the specific forms, so STOP can't shadow STOP MERGES/STOP VIEW. The new values push Type past the default magic_enum range, so enum_range is widened and the parser rejects the UNKNOWN/END sentinels. Otherwise SYSTEM UNKNOWN/SYSTEM END would parse into an AST whose formatting throws LOGICAL_ERROR instead of a syntax error.

  • Dispatch (InterpreterSystemQuery): one place resolves the table and branches streaming vs. RMV-aliasing on the new isStreamingStorage() predicate. isMessageQueue() couldn't be reused, because it excludes S3Queue/AzureQueue. ALL BACKGROUND fans out over both lock sets, skipping tables the caller can't access.

  • Abort boundary: only the read is abortable, not the insert. Aborting a half-inserted block would duplicate its rows, so a STOP/CANCEL mid-insert lets that block finish, keeping exactly-once.

  • Streaming mechanism: one StreamingBackgroundControl per streaming table, shared by every engine, holds three signals:

    • ActionBlocker: blocks future cycles. STOP/PAUSE set it, START clears it.
    • cancel_epoch: a monotonic counter bumped by STOP/CANCEL. Each consumer snapshots it on start and aborts once it advances. So a stale STOP can't poison a later read and concurrent cycles can't cancel each other. It covers an in-flight direct SELECT too, so STOP halts a manual read, otherwise the SELECT would keep consuming after a STOP.
    • refresh_epoch: a monotonic counter bumped by REFRESH. Each worker runs one cycle when it advances, even while blocked.

    The signals and verb logic are shared. Each engine's source then drops the uncommitted work its own way, so it is redelivered or reprocessed: Kafka v1 rewinds to the last committed offset (in place, no group rebalance, so one REFRESH re-reads the backlog), Kafka v2 drops uncommitted Keeper offset guard, RabbitMQ requeues (reject with AMQP::requeue), NATS JetStream skips the ack, S3Queue/AzureQueue cancel the pipeline and reset in-flight files when deduplication is on (default), otherwise in-flight batch finishes to avoid duplicates.

  • NATS JetStream acks after the insert (ManualAck=true): it used to ack on delivery, before the insert, so a STOP/CANCEL or failed insert had already acked the message and lost it. Acking after a successful insert makes NATS at-least-once: an aborted message stays unacked and is redelivered, like Kafka/RabbitMQ. Side effect: a direct SELECT no longer permanently consumes (opt in via nats_commit_on_select).

  • nats_commit_on_select (default false): a direct SELECT on JetStream leaves read messages unacked (redelivered, not consumed). true consumes the rows it returns. No-op for core NATS.

  • RBAC: a new SYSTEM BACKGROUND now parents existing SYSTEM VIEWS and a new SYSTEM STREAMING ENGINES. Privilege is resolved at runtime per engine (RMV → SYSTEM VIEWS, streaming → SYSTEM STREAMING ENGINES), and per table for ALL BACKGROUND, so it skips tables the caller lacks and never fails on access.

Known limitations / out of scope

  • ON CLUSTER is not supported (matching the SYSTEM ... VIEW aliases). Its getRequiredAccessForDDLOnCluster mapping is defensive only and, if ever enabled, must first be made engine-aware (SYSTEM STREAMING ENGINES for streaming tables).
  • Core NATS STOP/CANCEL are lossy (no replay). JetStream is at-least-once.
  • FileLog, WindowView, and an engine-agnostic WAIT are out of scope. SYSTEM WAIT VIEW stays RMV-only.

Tests

  • 04319_system_stop_all_background: every verb (per-table + ALL BACKGROUND) + RBAC.
  • 04320_parser_system_background_controls: parser round-trip plus negatives: ON CLUSTER rejected, non-controllable tables error with BAD_ARGUMENTS, SYSTEM UNKNOWN/SYSTEM END rejected as syntax errors (not a formatter LOGICAL_ERROR).
  • test_storage_{kafka,rabbitmq,nats,s3_queue}/test_system_stop.py: every verb per engine (incl. Kafka v2, AzureQueue, NATS JetStream). The in-flight boundary from both sides (STOP aborts a block held at the source, while a STOP/CANCEL during the insert commits/acks exactly once, or resets & reprocesses for S3Queue). REFRESH-runs-once. Live read-guard, no refresh-leak, no backlog. RBAC proves SYSTEM STREAMING ENGINES (not SYSTEM VIEWS) is required. A NATS-only test checks that nats_commit_on_select makes a direct SELECT consume the messages it reads only when enabled. test_storage_nats/ returns from master only to host this file plus a minimal broker/TLS harness.

Changelog category (leave one):

  • New Feature

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

Added engine-agnostic SYSTEM STOP, SYSTEM START, SYSTEM PAUSE, SYSTEM CANCEL, and SYSTEM REFRESH commands, and their ... ALL BACKGROUND server-wide forms, to control the background activity of Kafka, RabbitMQ, NATS, S3Queue/AzureQueue tables and refreshable materialized views through one unified interface. For refreshable materialized views they alias the existing SYSTEM ... VIEW commands. As part of supporting these controls on NATS, JetStream tables now acknowledge messages only after a successful insert (at-least-once, previously messages were auto-acknowledged on delivery and could be lost if the insert failed). A new nats_wait_for_flush_interval setting (default false, preserving the previous low-latency behaviour) optionally keeps a consumption cycle open for the whole flush interval instead of flushing as soon as the queue drains. A new nats_commit_on_select setting makes a direct SELECT on a JetStream table consume (acknowledge) the messages it reads.

Documentation entry for user-facing changes

  • Documented in docs/en/sql-reference/statements/system.md and docs/en/sql-reference/statements/grant.md and the autogenerated docs/en/operations/system-tables/grants.md and docs/en/operations/system-tables/privileges.md.

@CLAassistant

CLAassistant commented Jun 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f56697c]


AI Review

Summary

This PR adds unified SYSTEM STOP / START / PAUSE / CANCEL / REFRESH controls for streaming engines and refreshable materialized views, plus the shared background-control machinery behind them. The overall direction looks sound, but two contract gaps are still present in the current head: nats_commit_on_select does not reliably consume rows returned by early-finished direct reads, and the legacy Kafka / RabbitMQ / NATS direct-read guards still race with ATTACH MATERIALIZED VIEW.

Findings

⚠️ Majors

  • [src/Storages/NATS/NATSSource.cpp:72-103] [dismissed by author -- https://github.com/Add unified SYSTEM STOP/PAUSE/CANCEL/REFRESH for streaming engines and materialized views #107476#discussion_r3497002861] nats_commit_on_select still acknowledges JetStream messages only on EOF. A direct query that finishes downstream after the first returned chunk, for example SELECT ... LIMIT 1, returns a row from line 100, never reaches the EOF-only ack at line 102, and then destroys the source with dropConsumed in the destructor. That means the row the client already saw is redelivered later, which violates the new setting's documented contract that a direct SELECT consumes the messages it reads. Suggested fix: move the ack to a close/success path that still runs for early-finished queries, or force commit_on_select direct reads to drain before destruction.

  • [src/Storages/Kafka/StorageKafka.cpp:128-158], [src/Storages/RabbitMQ/StorageRabbitMQ.cpp:865-897], [src/Storages/NATS/StorageNATS.cpp:391-409] [dismissed by author -- https://github.com/Add unified SYSTEM STOP/PAUSE/CANCEL/REFRESH for streaming engines and materialized views #107476#discussion_r3525235192] The legacy streaming engines still enforce "cannot read with attached materialized views" with only a point-in-time getDependentViews check before creating direct-read sources. Unlike StorageKafka2, which now serializes direct reads and MV streamers with active_direct_readers / active_mv_streamers under consumers_mutex ([src/Storages/Kafka/StorageKafka2.cpp:418-457] and [src/Storages/Kafka/StorageKafka2.cpp:1187-1203]), these paths never register an in-flight direct read before consumers start getting claimed. An ATTACH MATERIALIZED VIEW that lands after the initial check can still let the user query and the new MV split one table's input concurrently. Suggested fix: port the Kafka2 handshake to Kafka, RabbitMQ, and NATS, or narrow the contract/tests/docs to a best-effort guard instead of a hard exclusion.

Tests
  • ⚠️ Add a JetStream regression with nats_commit_on_select = 1 where the query stops before EOF (LIMIT 1 is enough) and assert the returned row is acknowledged rather than redelivered.
  • ⚠️ Add an attach-race regression for the legacy Kafka / RabbitMQ / NATS engines: start a long direct read, attach a materialized view before all consumers are claimed, and prove the MV does not begin consuming until the direct read is gone.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fix the early-finish nats_commit_on_select path so returned rows are actually acknowledged, and close or explicitly de-scope the direct-read versus ATTACH MATERIALIZED VIEW race that still exists in Kafka, RabbitMQ, and NATS.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 15, 2026
Comment thread src/Storages/Kafka/KafkaSource.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 660/1025 (64.39%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

This PR only changes NATS streaming-engine settings, SYSTEM BACKGROUND/STREAMING ENGINES privilege plumbing, and their documentation — none of which touches the ClickBench query-execution hot path. The flagged improvements on Q10, Q11, and Q23 all sit off that path and all have noisy history, so they were downgraded to not_sure as variance rather than a real effect. The envelope-suppressed rows Q4 and Q15 check out: CPU time is essentially flat (2664 vs 2658 ms and 2607 vs 2599 ms) even though wall-clock moved ~-18%, confirming no real work-backed change. Q32 stays not_sure — borderline, with flat CPU and no changed code on its path.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 10 not_sure 179 150 -16.2% <0.0001 This PR changes streaming-engine background-activity control and privilege enums, not the ClickBench SELECT path; the -16.2% shift on an intrinsically noisy query is run-to-run variance, not a PR effect.
⚠️ 11 not_sure 226 173 -23.4% <0.0001 Q11 executes none of the streaming-engine or privilege code this PR changes, and its history is noisy, so the -23.4% improvement is not attributable to this PR.
⚠️ 23 not_sure 166 75 ×2.2 faster <0.0001 x2.2 faster looks large, but the query touches none of the changed code and its baseline measurements were very noisy, so this is variance rather than a PR effect.
⚠️ 32 not_sure 1314 1240 -5.6% 0.0003 aggregation: Heavy aggregation query; the two tests disagree (borderline) and CPU is essentially flat, and nothing in this PR touches its path, so not_sure is appropriate.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: a90c58fe-f358-4e4c-bb84-712195363787
  • MIRAI run: 5beba256-3473-40f9-a6d5-6ccd29762a8f
  • PR check IDs:
    • clickbench_461287_1784567509
    • clickbench_461293_1784567509
    • clickbench_461299_1784567509
    • tpch_adapted_1_official_461311_1784567509
    • tpch_adapted_1_official_461322_1784567510
    • tpch_adapted_1_official_461334_1784567509

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Jul 21, 2026
Merged via the queue into ClickHouse:master with commit d5b42ad Jul 21, 2026
348 of 351 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 21, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Jul 28, 2026
A REFRESH grants exactly one out-of-order streaming cycle. For RabbitMQ that
cycle starts the AMQP delivery loop asynchronously, so RabbitMQSource could
return zero rows on its first poll (buffer not filled yet) and break before
reaching the bounded waitForMessages path, wasting the single permit and
leaving the queued messages unconsumed until SYSTEM START.

A blocked-REFRESH background cycle now waits once (bounded by the flush
interval, cancel-aware) for the first message before returning empty. The
wait is a single shot, so an empty queue still returns promptly and the
one-REFRESH-one-cycle contract holds. Direct SELECTs and normal polling are
unchanged.

Fixes the flaky test_storage_rabbitmq/test_system_stop.py REFRESH tests added
in ClickHouse#107476.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Jul 30, 2026
`tests/integration/test_storage_nats/test_nats_core.py` and
`test_nats_jet_stream.py`, together with `common.py`, the test configs, the
Protobuf schema and the JSON reference, were removed in
ClickHouse#93616 - a re-removal of
ClickHouse#92140 after
ClickHouse#92155 had restored them. Restore
them and fix what has drifted since, so that they pass instead of timing out.

Four things had to be reconciled with the current `master`:

- Waiting for the consumer, not just for the view. Refusing a direct `SELECT`
  only proves that a materialized view is attached; the background streaming
  task subscribes to the subjects a moment later. Core NATS has no backlog, so
  messages published in that window are dropped and never reach the view - for
  example `test_nats_select` published 50 messages at `15:30:52.179` while the
  consumer subscribed at `15:30:52.215`, and then asserted on an empty view.
  `wait_for_mv_attached_to_table` now also waits for a fresh
  `Started streaming to N attached views` line, which the background task logs
  right after the consumer has subscribed. This is the same barrier
  `test_system_stop.py` already uses.

- `configs/nats.xml` and `nats_certs.sh` reappeared in `master` with
  ClickHouse#107476, which added
  `test_system_stop.py` to the same directory. Keep those versions and re-add
  the `<nats>` credentials that the restored tests rely on to `nats.xml`.

- `check_nats_is_available` no longer hangs on an unusable broker.
  `nats.connect` reports a TLS or an authentication failure through its error
  callback and then keeps retrying, so every NATS test ran into the 900 s pytest
  timeout with no indication of the cause - this is what all seven integration
  jobs of ClickHouse#100913 hit, because
  `ssl.create_default_context` enables `VERIFY_X509_STRICT` since Python 3.13
  (the test images switched in d308407, after the tests were removed) and
  the certificate of the time was rejected with `CA cert does not include key
  usage extension`. The certificate is already fixed in `master`; bound the
  connect attempt as well and log what the client saw.

- The `ruff` rules F401 (unused import) and F541 (`f`-string without
  placeholders) were enabled after the tests were removed, so drop the unused
  imports and the extraneous `f` prefixes. One expected error message lost its
  trailing period in the meantime, adjust the assertion accordingly.

Verified locally against a `master` release binary: both modules pass in full,
33 tests each.

Related: ClickHouse#100913

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ause-cancel-refresh

Add unified SYSTEM STOP/PAUSE/CANCEL/REFRESH for streaming engines and materialized views
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 22, 2026
…tup has finished

When the RabbitMQ setup of a table fails while it is loaded with mode > CREATE
(server restart, full-definition ATTACH), the constructor swallows the error and
`initialized` stays false. `startup()` then only activates `streaming_task` and
schedules `init_task`, whose `connectionFunc` retries the setup every 500 ms and
schedules the streaming task after a successful `initRabbitMQ()`. `threadFunc`
asserts that it never runs before that (`chassert(false)` in its `!initialized`
branch).

ClickHouse#107476 added `scheduleStreamingTasksImpl`, reached from
`IStreamingStorage::onActionLockRemove` (`SYSTEM START <table>`,
`SYSTEM START ALL BACKGROUND`) and `refreshBackgroundActivity`
(`SYSTEM REFRESH <table>` with a dependent view). It scheduled the streaming task
unconditionally, so on such a table `threadFunc` ran uninitialized and aborted
debug and sanitizer builds. Found by La Casa Del Dolor (amd_debug), STID 2508-3f0b,
after a server restart in which `initRabbitMQ()` failed with PRECONDITION_FAILED.

Schedule the task only when the table is initialized, the condition `startup()`
uses. `initialized` is atomic and only goes from false to true, so a reader that
sees false leaves the scheduling to `connectionFunc`. A START or REFRESH issued
before the setup is not lost: the action lock is already removed and the refresh
permit stays pending until the first cycle after the setup.

NATS keeps its streaming task deactivated until its consumers exist, so an early
`schedule()` is a no-op there; Kafka, Kafka2 and S3Queue have no such precondition.

The test runs the three statements against a broker-less table in clickhouse-local
(the shared test server cannot run SYSTEM START ALL BACKGROUND safely).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 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.

Parser accepts SYSTEM UNKNOWN/END Streamline the controls over background activity of certain table engines

7 participants