Repository navigation
Add unified SYSTEM STOP/PAUSE/CANCEL/REFRESH for streaming engines and materialized views - #107476
nikitamikhaylov merged 103 commits into
Conversation
…ing background-control mechanism + Kafka
…behavior on tables with no background activity and ON CLUSTER error test
…dRunCycle -> claimCycle
|
Workflow [PR], commit [f56697c] AI ReviewSummaryThis PR adds unified Findings
Tests
Final VerdictStatus: Minimum required actions: fix the early-finish |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 660/1025 (64.39%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (4 of 43)
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
|
d5b42ad
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]>
`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]>
…ause-cancel-refresh Add unified SYSTEM STOP/PAUSE/CANCEL/REFRESH for streaming engines and materialized views
…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]>
Closes: #102707
Closes: #108104
One unified set of
SYSTEMcommands to control the background activity of the streaming engines (Kafka,RabbitMQ,NATS,S3Queue/AzureQueue) and refreshable materialized views (RMV). Previously RMV had its ownSYSTEM ... VIEWcommands and the streaming engines had no per-table SQL control.On an RMV the verbs are aliases of the existing
SYSTEM ... VIEWcommands.ALL BACKGROUNDapplies 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:
STOP= PAUSE + CANCELPAUSECANCELSTARTSTOP/PAUSEREFRESHThe abort is best-effort:
STOP/CANCELare 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 likePAUSE), aborting it then would duplicate the already-inserted rows.S3Queue/AzureQueueare 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.STOP/CANCELabortProcessed* With deduplication off (non-default), the in-flight batch finishes and commits instead.
REFRESHruns immediately on a streaming table (even while stopped, then re-blocks). On a stopped RMV it defers untilSTART, likeSYSTEM REFRESH VIEW.Design notes
AST: scope lives in the
Typeenum (5 basic verbs + 5*_ALL_BACKGROUND). Basic verbs match in a fallback after the specific forms, soSTOPcan't shadowSTOP MERGES/STOP VIEW. The new values pushTypepast the defaultmagic_enumrange, soenum_rangeis widened and the parser rejects theUNKNOWN/ENDsentinels. OtherwiseSYSTEM UNKNOWN/SYSTEM ENDwould parse into an AST whose formatting throwsLOGICAL_ERRORinstead of a syntax error.Dispatch (
InterpreterSystemQuery): one place resolves the table and branches streaming vs. RMV-aliasing on the newisStreamingStorage()predicate.isMessageQueue()couldn't be reused, because it excludesS3Queue/AzureQueue.ALL BACKGROUNDfans 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/CANCELmid-insert lets that block finish, keeping exactly-once.Streaming mechanism: one
StreamingBackgroundControlper streaming table, shared by every engine, holds three signals:ActionBlocker: blocks future cycles.STOP/PAUSEset it,STARTclears it.cancel_epoch: a monotonic counter bumped bySTOP/CANCEL. Each consumer snapshots it on start and aborts once it advances. So a staleSTOPcan't poison a later read and concurrent cycles can't cancel each other. It covers an in-flight directSELECTtoo, soSTOPhalts a manual read, otherwise theSELECTwould keep consuming after aSTOP.refresh_epoch: a monotonic counter bumped byREFRESH. 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
REFRESHre-reads the backlog), Kafka v2 drops uncommitted Keeper offset guard, RabbitMQ requeues (rejectwithAMQP::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 aSTOP/CANCELor 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 directSELECTno longer permanently consumes (opt in vianats_commit_on_select).nats_commit_on_select(defaultfalse): a directSELECTon JetStream leaves read messages unacked (redelivered, not consumed).trueconsumes the rows it returns. No-op for core NATS.RBAC: a new
SYSTEM BACKGROUNDnow parents existingSYSTEM VIEWSand a newSYSTEM STREAMING ENGINES. Privilege is resolved at runtime per engine (RMV →SYSTEM VIEWS, streaming →SYSTEM STREAMING ENGINES), and per table forALL BACKGROUND, so it skips tables the caller lacks and never fails on access.Known limitations / out of scope
ON CLUSTERis not supported (matching theSYSTEM ... VIEWaliases). ItsgetRequiredAccessForDDLOnClustermapping is defensive only and, if ever enabled, must first be made engine-aware (SYSTEM STREAMING ENGINESfor streaming tables).STOP/CANCELare lossy (no replay). JetStream is at-least-once.FileLog,WindowView, and an engine-agnosticWAITare out of scope.SYSTEM WAIT VIEWstays 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 CLUSTERrejected, non-controllable tables error withBAD_ARGUMENTS,SYSTEM UNKNOWN/SYSTEM ENDrejected as syntax errors (not a formatterLOGICAL_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 (STOPaborts a block held at the source, while aSTOP/CANCELduring the insert commits/acks exactly once, or resets & reprocesses forS3Queue).REFRESH-runs-once. Live read-guard, no refresh-leak, no backlog. RBAC provesSYSTEM STREAMING ENGINES(notSYSTEM VIEWS) is required. A NATS-only test checks thatnats_commit_on_selectmakes a directSELECTconsume 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):
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, andSYSTEM REFRESHcommands, and their... ALL BACKGROUNDserver-wide forms, to control the background activity ofKafka,RabbitMQ,NATS,S3Queue/AzureQueuetables and refreshable materialized views through one unified interface. For refreshable materialized views they alias the existingSYSTEM ... VIEWcommands. 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 newnats_wait_for_flush_intervalsetting (defaultfalse, 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 newnats_commit_on_selectsetting makes a directSELECTon a JetStream table consume (acknowledge) the messages it reads.Documentation entry for user-facing changes
docs/en/sql-reference/statements/system.mdanddocs/en/sql-reference/statements/grant.mdand the autogenerateddocs/en/operations/system-tables/grants.mdanddocs/en/operations/system-tables/privileges.md.