Skip to content

Fix SYSTEM REFRESH on a stopped RabbitMQ table not consuming the backlog - #111480

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-rabbitmq-refresh-empty-cycle-permit
Jul 28, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-rabbitmq-refresh-empty-cycle-permit

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix SYSTEM REFRESH on a stopped RabbitMQ table sometimes failing to consume the queued backlog. A REFRESH grants exactly one out-of-order streaming cycle, but that cycle could return immediately with zero rows because the AMQP delivery loop had only just been started asynchronously, wasting the single permit and leaving the messages unconsumed until the next SYSTEM START.

Description

Found by the flaky integration tests test_storage_rabbitmq/test_system_stop.py::test_refresh_survives_unready_dependencies and ::test_refresh_runs_once_while_start_keeps_consuming, both added by #107476. Reported as a master regression by @alexey-milovidov.

Report (rabbitmq, master): https://s3.amazonaws.com/clickhouse-test-reports/REFs/master/d4f24b7eb15117fcbace307be50d8054c786580a/integration_tests_amd_asan_ubsan_db_disk_old_analyzer_6_6/ (got 1 row, expected 6, passed on retry).

Root cause: while a stream is stopped, SYSTEM REFRESH grants exactly one out-of-order streamToViews cycle. That cycle builds a RabbitMQSource and starts the AMQP delivery loop asynchronously. RabbitMQSource::generateImpl then checks consumer->hasPendingMessages() on its first poll; the loop has not delivered anything yet, so the source returns 0 rows and breaks immediately, never reaching the bounded waitForMessages path (which only runs after at least one row was read). The single REFRESH permit is spent on an empty cycle and, because the stream is still stopped, the queued messages stay unconsumed.

Fix: a blocked-REFRESH background cycle now asks the source to wait once (bounded by the flush interval, cancel-aware, via the existing waitForMessages) for the first message before returning empty. The wait is a single shot, so a genuinely empty queue still returns promptly and the "one REFRESH == one cycle" contract holds. Direct SELECTs and normal continuous polling are unchanged (they build the source at a separate call site and never set the flag).

Scope: RabbitMQ only. Kafka polls the broker synchronously and NATS keeps its cycle open via nats_wait_for_flush_interval, so neither has this async-first-poll gap; CIDB shows RabbitMQ is the only engine whose test_system_stop REFRESH tests fail on master.

Validated locally: the failing test reproduces at about 1/6 without the fix and passes 15/15 with it; the sibling REFRESH test passes 8/8.

Note: the separate S3Queue server abort under ObjectStorageQueueSource::FileIterator::next that @alexey-milovidov saw on #100332 is a pre-existing hash-ring out-of-bounds bug already fixed by #108977, not by this PR.

Version info

  • Merged into: 26.8.1.279-master (included in 26.8 and later)
  • Backported to: 26.7.22.6

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. test_storage_rabbitmq/test_system_stop.py::test_refresh_survives_unready_dependencies fails ~1/6 on unfixed master; the empty-first-poll mechanism is isolated from the CI master server log (one "Started streaming"/"Processed 0 rows" at ATTACH, then only growing reschedules).
b Root cause explained? Yes. SYSTEM REFRESH while stopped grants one streamToViews cycle; that cycle starts the AMQP loop asynchronously, so RabbitMQSource::generateImpl finds an empty buffer on its first poll and breaks with 0 rows before reaching waitForMessages, wasting the single permit while the stream stays blocked.
c Fix matches root cause? Yes. The blocked-REFRESH cycle now waits once (bounded, cancel-aware) for the first delivery before returning empty. No change to the permit machinery (a re-credit approach was considered and rejected).
d Test intent preserved / new tests? Yes. No test weakened. The two existing regression tests added in #107476 (test_refresh_survives_unready_dependencies, test_refresh_runs_once_while_start_keeps_consuming) still assert the same contract and now pass reliably; they are the fails-without/passes-with tests.
e Both directions? Yes. Fails-without 1/6; passes-with 15/15 (survives) + 12/12 (survives, post-review build) + 8/8 (runs_once sibling).
f General, not a narrow patch? Yes for the engine class. Scoped to RabbitMQ: Kafka polls the broker synchronously and NATS holds its cycle open via nats_wait_for_flush_interval, so neither has the async-first-poll gap; CIDB confirms RabbitMQ is the only engine with a master failure of this test. One fix covers both affected RabbitMQ tests.
g Generalizes across inputs? Yes. The wait is bounded by the existing execution-time budget and cancel-aware; rabbitmq_flush_interval_ms = 0 takes the no-deadline path (mirrors the existing empty-poll wait), a genuinely empty queue times out once then breaks, and a stopped consumer skips the wait.
h Backward compatible? Yes. No setting default, no on-disk/wire/format change. Behavior change is limited to a blocked-REFRESH background cycle waiting up to the already-configured flush interval for the first message.
i Invariants/contracts preserved? Yes. REFRESH still equals exactly one cycle (the flag is single-shot, so no extra cycle is claimed and an empty queue does not spin); the direct-SELECT path is untouched; the cancel epoch is honored during the wait.

Session id: cron:clickhouse-author-slot-0:20260722-190100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck; delta recheck raised 0 new findings).

# Sev Finding Verdict Evidence / action
1 ❌ An explicit rabbitmq_flush_interval_ms = 0 still wasted the permit: the first branch computed a zero wait budget and skipped the wait AGREE — fixed Mirrored the existing empty-poll path: when max_execution_time_ms == 0, wait with std::nullopt (no deadline); also added a !consumer->isConsumerStopped() guard. Rebuilt, re-validated 12/12 pass.
2 ❌ The synchronous first-message wait can starve the shared message-broker pool under SYSTEM REFRESH ALL BACKGROUND across many stopped tables DISAGREE Pre-existing pattern, not introduced here: the normal streaming path already blocks a getMessageBrokerSchedulePool() worker in consumer->waitForMessages() on every empty follow-up poll (RabbitMQSource.cpp:397-402); the delivery loop is a separate pool task that signals the CV. This diff adds one bounded, cancel-aware wait on the first poll of a blocked-REFRESH cycle only; a saturated pool degrades to the prior behavior (permit lost on timeout), not a deadlock. Re-crediting the permit on a failed loop start is the band-aid the approach review already rejected.
3 💡 The same rationale was repeated in three long comments AGREE — fixed Trimmed to a concise invariant at each site; full rationale lives in the commit message and PR body.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-author-slot-0:20260722-190100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @kssenii - could you review this? It fixes SYSTEM REFRESH on a stopped RabbitMQ table wasting its single permit on an empty first poll (the AMQP delivery loop is started asynchronously, so RabbitMQSource::generateImpl returned 0 rows before any message arrived and the queued backlog stayed unconsumed). The blocked-REFRESH cycle now waits once for the first delivery; direct SELECTs and normal polling are unchanged.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b4cef25]

Summary: ✅


AI Review

Summary

This PR fixes the stopped-RabbitMQ SYSTEM REFRESH path by distinguishing a genuinely claimed blocked-refresh cycle from an ordinary cycle and letting only that admitted cycle self-drive the AMQP loop when the background message-broker worker is starved. I re-checked the current head against the full PR diff and all prior discussion, including the four existing inline threads, and I did not find any remaining correctness, compatibility, or test-coverage issue that merits a new inline review comment.

Final Verdict

✅ No new inline findings on the current head.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
…locked

The first-message wait added for SYSTEM REFRESH on a stopped RabbitMQ table
parked the streaming source on the consumer's condition variable. Delivery of
that message comes from the RabbitMQLoopingTask, which runs in the same
MessageBrokerSchedulePool. While the stream is stopped the looping task may
never get a pool worker (a SYSTEM REFRESH ALL BACKGROUND fan-out across more
tables than background_message_broker_schedule_pool_size can occupy them all),
so the parked cycle only wakes on its timeout with zero rows and the backlog
stays queued. With rabbitmq_flush_interval_ms=0 the wait was also unbounded
(SANITY_TIMEOUT, 10 min).

Have the blocked-REFRESH cycle drive the event loop itself via
RabbitMQHandler::iterateLoop() (a no-op when the looping task already owns the
loop, since it try_locks the handler startup mutex) on every empty poll, not
just the first, so backlog messages after the first are drained too. This
removes the dependency on a second pool worker for the whole cycle. Each empty
poll is bounded by a fresh per-poll idle budget rather than the shared
construction-time stopwatch: with more than one consumer the sources share a
single pipeline thread and run serially, so a shared budget would let the first
source spend it all and starve the rest.

Add a regression test on a node with a single message-broker worker
(background_message_broker_schedule_pool_size=1) and two consumers that
deterministically strands the backlog without the fix.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (bot-feedback fixup) (click to expand)

Gate B (independent second-model code review) on the fixup commit, two rounds. All findings verified against the code before acting.

Round 1 (3 findings)

id severity verdict resolution
multi-consumer-deadline blocker AGREE With num_consumers>1 the sources share one pipeline thread; a shared construction-time budget let the first source exhaust it and starve the rest. Fixed: per-source drive budget; self-driving path no longer gated by the shared total_stopwatch. Test upgraded to 2 consumers.
single-worker-bootstrap major AGREE Test no longer relies on normal single-worker consumption for an initial row; it establishes the table stopped, then REFRESHes.
repeated-starvation-comments nit AGREE Trimmed duplicated comments; mechanism documented once at driveLoopUntilMessage, motivation in the commit message.

Round 2 (stateful re-review, 2 findings)

id severity verdict resolution
cycle-budget-reset blocker AGREE Per-poll reset removed the absolute cycle bound. Fixed: absolute per-source drive deadline started on the source's first empty poll (bounds total cycle time, stays fair across serially-run consumers).
refresh-test-not-discriminating major AGREE The node loaded parallel_view_processing=1, so sources need not run serially. Added a users profile pinning parallel_view_processing=0 to force the serial multi-consumer path.

Both-directions verification (integration runner): pre-fix baseline strands the backlog (0 of 20 rows); with the fix it drains completely.

… empty ones

The self-driving blocked-REFRESH cycle (drive_loop_on_worker) skipped the main-loop
time-limit check (it was gated by !drive_loop_on_worker) and only consulted the
per-source drive budget inside driveLoopUntilMessage, which runs only on an empty poll.
So a blocked SYSTEM REFRESH with a steady backlog (every poll returns rows) never
re-entered driveLoopUntilMessage and never checked elapsed time, draining up to
rabbitmq_max_block_size instead of staying bounded by the flush interval.

Start the per-source drive_stopwatch at cycle entry and consult driveBudgetMs() in the
main loop for the drive path, so the absolute deadline is enforced on every iteration
regardless of poll outcome. Cap the empty-poll wait slice by the remaining budget so the
wait honors the same deadline. A large backlog now drains across successive REFRESH
cycles, each bounded by the flush interval, matching the non-driving path.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (Gate B, round 2) — click to expand

Independent review of commit 4e523a7 (the steady-backlog deadline fix). 5 findings; adjudicated:

# Finding Severity Verdict
1 self-drive-frame-throttle: 50ms wait throttles delivery to ~4 msg/s blocker DISAGREE (code)
2 cycle-budget-multiplied: per-source deadline -> N x flush_interval serial cycle blocker DISAGREE (evidence)
3 refresh-test-contract-gaps: test not deterministic for multi-consumer/cancel major DISAGREE (evidence)
4 repeated-starvation-comments: rationale repeated across sites nit PARTIAL AGREE (trimmed)
5 missing-changelog-entry nit DISAGREE (false positive)
  1. uv_run(NOWAIT) drains all socket-ready frames per call: AMQP-CPP ConnectionImpl::parse loops while (processed < buffer.size()) over every complete frame (connectionimpl.cpp:120-152), pushing all complete messages to received; waitForMessages returns on the first cv.notify_one, not a fixed sleep. The one-frame-per-iteration premise does not hold for a buffered backlog.
  2. Per-source is deliberate: a single shared deadline (the proposed fix) lets the first of N serial sources spend it all and starve the rest, which is the sibling-starvation this PR fixes. Default rabbitmq_num_consumers=1 -> per-source == cycle; the multi-consumer worst case is bounded by the outer 60s MAX_THREAD_WORK_DURATION_MS.
  3. The test already discriminates the regression in both directions (pre-fix strands 0/20, post-fix drains 20/20). Asserting per-consumer distribution (consistent-hash) or a time cap would be non-deterministic.
  4. Trimmed the one redundant comment the delta introduced (the drive_stopwatch member doc); the full rationale lives in the commit message.
  5. The live PR body already carries a complete changelog entry; the gate read a partial scratch contract.

…ycle

A blocked SYSTEM REFRESH cycle drives the AMQP event loop itself (the source
calls iterateLoop while draining, and acks go through iterateLoop too), so it
does not need the background RabbitMQLoopingTask. But streamToViews still
started that task (once before executing the pipeline and once at the end of a
successful cycle), and with a single message-broker worker
(background_message_broker_schedule_pool_size=1) the looping task then spins
uv_run on the only worker forever, so the streaming task can never be scheduled
again and every later SYSTEM REFRESH or SYSTEM START is stuck.

Skip starting the background loop on the self-driving (blocked REFRESH) path.
The table is stopped, so no continuous streaming should follow the cycle anyway.

Also right-size test_refresh_drains_backlog_with_single_broker_worker: one
blocked REFRESH cycle is bounded by each serial source's flush-interval drive
budget, and single-worker self-driven delivery is paced, so a 20-message backlog
did not fit one cycle and stranded a message. Publish a small backlog (two per
consumer) that fits the budget with margin, and extend the test to issue a
second REFRESH and a START so it also covers the worker no longer being
monopolized.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 Gate B passes, 5 distinct findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ A blocked REFRESH cycle restarts the background looping task; with a single message-broker worker it monopolizes the sole worker so no later REFRESH/START runs (StorageRabbitMQ::streamToViews) AGREE — fixed @ bca450d5 Reproduced: the strengthened test fails at the 2nd REFRESH (expected 8, got 4) on the pre-fix binary; server log shows Background loop started holding the worker ~73s. Fixed by skipping both startLoop() calls (before execute + end-of-cycle) on the self-drive path; the source drives the loop itself and acks via iterateLoop(). Passes 15/15 with the fix.
2 ❌ Self-drive can block indefinitely inside another consumer's delivery callback if a sibling received queue fills during iterateLoop (RabbitMQSource::driveLoopUntilMessage) DISAGREE Pre-existing property of the shared connection, not introduced here: the normal streaming path already runs the same uv_run via RabbitMQHandler::startLoop, dispatching the same connection-wide callbacks. It also requires >100000 messages (queue_size = max(100000, max_block_size)) buffered on one inactive sibling queue within a single cycle. Out of scope for this flaky-test fix (a separate pre-existing hardening, e.g. broker QoS).
3 ⚠️ Setup races SYSTEM STOP against the initial normal streaming cycle DISAGREE Not reachable: the view is attached while the exchange is empty and STOP is issued before any publish, so every initial cycle reads 0 rows and hits the "Queues are empty" early return (return false) before the end-of-cycle startLoop. Empirically 0 Background loop started for the table pre-STOP across a 12-run batch.
4 ⚠️ Aggregate row-count oracle does not prove both serial sources get independent drive budgets DISAGREE The suggested remedy (assert per-consumer counts via _channel_id) would itself be flaky: the consistent_hash exchange gives no guaranteed 2/2 split. The per-source-budget property is already covered — the original 20-message strand proved a shared budget fails, and the shipped drive_stopwatch is per-source. Core oracles (full backlog drains in one REFRESH; a second REFRESH also drains) are deterministic.
5 ⚠️ Final START assertion cannot validate continuous consumption with one worker (the tail contradicts the test's own premise) AGREE — fixed @ bca450d5 Correct: the START tail expected continuous streaming the single worker cannot provide (it drained only via slow rescheduled cycles). Removed it; the second REFRESH already proves the worker is reusable. Replaced with a final stable-count assertion.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-author-slot-3:20260723-054501

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Same binary: test_refresh_drains_backlog_with_single_broker_worker fails deterministically before the fix (strand at first REFRESH with the old 20-message backlog; and, once the backlog fits one cycle, the 2nd REFRESH stalls at expected 8, got 4), and passes after.
b Root cause explained? A blocked SYSTEM REFRESH runs exactly one streamToViews cycle that self-drives the AMQP loop. streamToViews also started the background RabbitMQLoopingTask (before executing and at end-of-cycle); with background_message_broker_schedule_pool_size=1 that task then spins uv_run on the only worker, so the streaming task can never be scheduled again and every later REFRESH/START is stuck.
c Fix matches root cause? Yes. Skip starting the background looping task on the self-drive (blocked REFRESH) path — the source drives the loop itself and acks via iterateLoop, so the task is unneeded, and the table is stopped so no continuous streaming should follow.
d Test intent preserved / new tests added? Yes. The regression test keeps the single-worker + two-consumer + STOP + one-REFRESH structure and the full-backlog-drain assertion, and is extended with a second REFRESH (guards this worker-monopolization bug) plus a stable-count check. No assertion weakened.
e Both directions demonstrated? Yes. Control binary (no startLoop guards): test FAILS at the 2nd REFRESH (expected 8, got 4). Fixed binary: PASSES 15/15 across batches (plus 5/5 on the combined tree).
f Fix is general across code paths? Yes. Both startLoop() sites in streamToViews (pre-execute and end-of-cycle) are guarded; the direct-SELECT read() path has its own separate startLoop and is intentionally untouched (it is not a blocked self-drive cycle).
g Fix generalizes across inputs? Yes. The guard keys off drive_loop_on_worker (set only for a blocked REFRESH cycle), independent of message count, consumer count, or flush interval; verified with 1 and multiple messages per consumer across repeated runs.
h Backward compatible? Yes. No setting default, on-disk/wire/replication format, or public behavior change. Only an internal background-task scheduling decision on the blocked-REFRESH path; normal streaming, direct SELECT, PAUSE, CANCEL, STOP, and non-blocked REFRESH are unchanged.
i Invariants and contracts preserved? Yes. Upholds the documented "one SYSTEM REFRESH = one streaming cycle" contract (docs system.md; Kafka test_two_queued_refreshes_run_two_cycles). drive_stopwatch is always emplaced before any use on the self-drive path; the cancel epoch and stopped-consumer checks are unchanged.

Session id: cron:clickhouse-author-slot-3:20260723-054501

@groeneai

Copy link
Copy Markdown
Collaborator Author

Update: pushed bca450d5 on top of the earlier commits. While validating the single-broker-worker regression test I found a real engine bug in the blocked-SYSTEM REFRESH path, so this PR now also carries a small StorageRabbitMQ fix (not just the test).

  • Bug: a blocked-REFRESH cycle drives the AMQP loop itself, but streamToViews still started the background RabbitMQLoopingTask (before executing and again at end-of-cycle). With background_message_broker_schedule_pool_size=1 that task then spins uv_run on the sole worker, so the streaming task is never rescheduled and every later REFRESH/START is stuck.
  • Fix: skip starting the background loop on the self-drive (blocked REFRESH) path. Normal streaming, direct SELECT, PAUSE, CANCEL, STOP, and non-blocked REFRESH are unchanged.
  • The regression test was right-sized (a 20-message backlog did not fit one cycle's per-source flush-interval drive budget on a single worker) and extended with a second REFRESH that guards the worker-monopolization bug above.

Both directions validated locally: the test fails at the second REFRESH without the fix (expected 8, got 4) and passes 15/15 with it. Adjudication of the internal review is in the collapsed comment above.

…self-driving path

The self-driving blocked-REFRESH path bounded the whole cycle by driveBudgetMs()
(the flush interval, or a 5s default when the flush interval is 0). But an explicit
rabbitmq_flush_interval_ms=0 means "no per-cycle timeout" and is preserved as 0 through
streamToViews, so the normal streaming path leaves such a cycle unbounded (it drains up
to max_block_size). The drive path instead cut a flush=0 stopped table off after 5s,
stranding a large or slow backlog until the next REFRESH/START.

Make the whole-cycle deadline honor max_execution_time_ms (0 == unlimited) on both paths:
the generateImpl time-limit check now uses max_execution_time_ms directly, so flush=0
drains the full backlog up to max_block_size like the normal path. The finite
driveBudgetMs() fallback is kept only where it must not spin forever: the per-wait idle
window in driveLoopUntilMessage now measures a fresh per-call Stopwatch when flush=0, so
an empty queue still releases the REFRESH permit after the default wait while a live
backlog (messages always pending) never idles and drains in full. flush>0 behavior is
unchanged (cumulative drive_stopwatch vs the flush interval).

The single-broker-worker regression test now uses flush_interval_ms=0 with a 20-message
backlog per REFRESH: it drains fully only when no finite whole-cycle cap truncates the
paced single-worker drain, and it keeps the second-REFRESH assertion so a self-driving
cycle must not leave the looping task holding the sole worker.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator Author
Internal second-model review log (round 3, commit cb33e54) - click to expand

Gate B (independent second-model review, engine=codex) on the round-3 delta (flush_interval_ms=0 unlimited-cycle fix). 6 findings, all adjudicated DISAGREE with evidence (4 are re-raises of round-2 findings, re-verified; 1 new, refuted as unreachable + out of scope; 1 stale-contract false positive).

# id sev verdict reason
1 cycle-budget-multiplied blocker DISAGREE per-source budget is the intended sibling-starvation fix; flush=0 drain-to-max_block_size is the documented unlimited-cycle contract; the proposed shared finite deadline would itself re-break flush=0 and reintroduce sibling starvation. One REFRESH = one block-bounded cycle (outer loop breaks after one drive cycle).
2 self-drive-frame-throttle blocker DISAGREE AMQP-CPP ConnectionImpl::parse drains ALL complete frames in the socket buffer per iterateLoop (connectionimpl.cpp:120-152); the 50ms wait is hit only when no further complete frame is available. Round-1 drained 20 messages through this loop.
3 direct-reader-loop-ownership major DISAGREE Unreachable: a direct SELECT requires zero attached views (read() throws otherwise) while the self-driving cycle requires >=1 view, so the two cannot be active together; loop_mutex + readers_count guard the narrow attach race. Also targets the loop-cleanup commit, not this delta.
4 refresh-test-contract-gaps major DISAGREE per-channel-distribution assertions are non-deterministic; the test already discriminates the fix (full drain only with it) and now also exercises the second-REFRESH loop-cleanup path.
5 repeated-starvation-comments nit DISAGREE the two comments added in this delta state the local invariant at the call site (motivation lives in the commit message); the cross-layer duplication and spelling nits are on pre-existing comments outside this delta.
6 missing-changelog-entry nit DISAGREE the live PR body has a complete Bug Fix changelog entry; the gate read a stale local contract file.

Build-ID cb33e54 = 11c0b7f7a548a801e3c23e3e53e52fd7c6f1cfc1.

Session id: cron:clickhouse-maint-slot-9:20260723-072300

…ing path too

A blocked SYSTEM REFRESH cycle sets drive_loop_on_worker and drives the AMQP
event loop from the source as a fallback for a starved MessageBrokerSchedulePool.
An earlier commit additionally stopped starting the background RabbitMQLoopingTask
on that path. But self-drive alone is paced (one iterateLoop + a short poll per
message), so with a finite rabbitmq_flush_interval_ms a single REFRESH drained
only the first queued message before the per-cycle budget elapsed: the backlog
was left queued and REFRESH looked like it consumed one row instead of the whole
snapshot.

Start the looping task on the self-driving path again. When a pool worker is free
it delivers the whole backlog within the budget (the pre-existing behavior); when
the pool is starved the task simply stays queued and the source's own self-drive
still makes progress (iterateLoop and startLoop are serialized by the handler's
startup_mutex, so uv_run is never driven concurrently). The task is deactivated
unconditionally after the cycle and, on the self-driving path, is not restarted
afterwards, so a single message-broker worker is not monopolized and later
REFRESH/START cycles still run.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed a PR-caused CI regression on the previous head (cb33e54).

Two integration tests failed deterministically across all 6 build variants (tsan/asan/msan/coverage/arm): test_refresh_runs_once_while_start_keeps_consuming and test_refresh_survives_unready_dependencies, both asserting 2 == 6 (a single SYSTEM REFRESH drained only 1 of a 5-message backlog). Not a container flake: 28+ sibling RabbitMQ tests pass in the same jobs, and CIDB bisects the two failures cleanly to bca450d5.

Root cause: bca450d5 made two changes to streamToViews, but only one was needed. The necessary one skips re-starting the background loop after a blocked-REFRESH cycle (so a single message-broker worker is not monopolized). The other also stopped starting the loop before the cycle, leaving the source's own paced self-drive as the only delivery path; under a finite rabbitmq_flush_interval_ms that drains ~1 message per cycle. The CI server log confirms it: the REFRESH cycle ran its full ~513ms budget and reported "Processed 1 rows".

Fix (1 file, 4 lines): start the background looping task on the self-driving path again. When a pool worker is free it delivers the whole backlog within the budget (the pre-bca450d5 behavior these two tests already passed on); when the pool is starved the task just stays queued and the source's self-drive still makes progress. iterateLoop and startLoop are serialized by the handler's startup_mutex, so uv_run is never driven concurrently. The task is still deactivated after the cycle and not restarted on the self-driving path, so the single-worker regression test (test_refresh_drains_backlog_with_single_broker_worker) keeps passing.

Local live re-verification is blocked by a host RabbitMQ-container boot flake (broker "Time to start RabbitMQ: 64594 ms" vs the harness window; a standalone probe also did not reach await_startup in 120s on this host), so this relies on CIDB: the post-fix code path is byte-identical to the r1/r2 head where both tests passed. Upstream CI runs the full suite with a healthy broker.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (Gate B) adjudication for the ci-fix delta

Delta reviewed: 4 lines in StorageRabbitMQ.cpp (restore pre-execute startLoop, keep the post-cycle skip). Engine codex. 6 findings, all re-raises of findings from earlier rounds, all concerning code OUTSIDE this delta; re-verified on the merits, all DISAGREE.

id sev verdict reason
self-drive-frame-throttle blocker DISAGREE Concerns the paced self-drive path. This delta FIXES that slowness by restoring the background loop for the free-worker case; AMQP-CPP drains all ready frames per iterateLoop, the wait fires only on no-progress. RabbitMQSource.cpp untouched.
cycle-budget-multiplied blocker DISAGREE Per-source budget is the deliberate sibling-starvation fix; default num_consumers=1, outer 60s guard caps worst case. Not in this delta.
direct-reader-loop-ownership major DISAGREE Direct-select throws if any view is attached; the drive cycle only runs with a view attached, so they are mutually exclusive. This delta only starts the loop in more cases, so reader liveness is not worsened. Post-cycle deactivate/stopLoopIfNoReaders untouched.
refresh-test-contract-gaps major DISAGREE Proposed per-channel and finite-cap asserts are racy; the single-worker test already discriminates both directions and the 2nd-REFRESH path. Test file untouched.
repeated-starvation-comments nit DISAGREE RabbitMQSource.h untouched by this delta; the driveBudgetMs comment already describes the 0 case correctly (no per-cycle budget).
missing-changelog-entry nit DISAGREE The live PR body has a complete Bug Fix changelog entry; the gate read a stale scratch contract.

…EFRESH

`threadFunc` decided the self-driving path with a fresh `stream_control.isBlocked()`
read taken after `claimCycle` had already admitted the cycle. A `SYSTEM STOP` or
`SYSTEM PAUSE` landing in that window retroactively converted an *ordinary* cycle
into the self-driving one, so it would wait up to the flush interval for future
deliveries - broadening `PAUSE` from "let the current cycle finish" into "maybe run
one implicit refresh", letting rows published after the pause still be consumed.
The symmetric case was wrong too: a `SYSTEM START` racing in right after a blocked
`REFRESH` permit was claimed would drop the self-driving path and waste the permit,
which is the very bug this pull request fixes.

`StreamingBackgroundControl::claimCycle` now optionally reports whether the cycle was
admitted by consuming a REFRESH permit *while blocked*, sampled together with the
claim itself, and `StorageRabbitMQ::threadFunc` drives the loop only on that flag
(consumed with `std::exchange`, so the following ordinary iterations of the inner
streaming loop keep the fast empty return).
@alexey-milovidov

Copy link
Copy Markdown
Member

@alexey-milovidov branch updated as requested — head 42b40ad3ca5 → bf028298597.

1. Merged master (clean, zero conflicts). All three owners of the previously-red unrelated checks have landed, so those reds should clear on this run:

Previously-red check / test Fixing PR Status
Upgrade check — New + Changed settings not in settings changes history (join_runtime_filter_min_probe_rows) #111671 MERGED 2026-07-24 (entry now present in SettingsChangesHistory.cpp)
Upgrade check — Error message in clickhouse-server.log (system.metric_log rotation ALTER exceeds max_query_size) #111703 MERGED 2026-07-24 (21436191097)
Integration test_replicated_database::test_replicated_table_structure_alter (chronic flaky, #110036) #111029 MERGED 2026-07-24

2. Addressed the one remaining unresolved review thread (clickhouse-gh, the SYSTEM PAUSE race on the drive_loop_on_worker = isBlocked() gating) — implemented exactly the suggested shape: the "claimed blocked REFRESH" flag is now propagated out of StreamingBackgroundControl::claimCycle, sampled atomically with the claim, instead of being re-read after the cycle was already admitted. This closes the race in both directions (a STOP/PAUSE no longer turns an ordinary cycle into an implicit refresh; a START no longer wastes a just-claimed refresh permit). Details in the thread and in the commit message.

Verified locally: all 6 affected translation units (StorageRabbitMQ, RabbitMQSource, StorageKafka, StorageKafka2, StorageNATS, StorageObjectStorageQueue — the other users of claimCycle) build with exit 0 and no warnings. The RabbitMQ behaviour change is confined to the blocked-REFRESH path, so the existing test_system_stop.py REFRESH tests remain the coverage.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — bf02829

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log Failed to read version metadata for part all_1_5_4_1: Code: 27 ... expected '\n' before: 'version: 1 storing_version: 0 ...' then Code: 246 ... Part all_5_6_1_0 intersects previous part all_1_5_4_1 ... (CORRUPTED_DATA) on test_1.t_plt_evict_reinsert. The part_loading_tree_rollback tests fabricate a plaintext txn_version.txt that the previous release cannot parse once the table lands on an object-storage default policy #111772 (ours, merged 2026-07-27)
Sync - CH Inc sync (private, not actionable)

The Bugfix validation (integration tests, amd64 / aarch64) rows that CIDB reports for
test_storage_rabbitmq/test_system_stop.py on this head are the master-binary side of the bugfix
validation, which must fail for the check to prove the regression test catches the bug: both jobs report
check_status = success. They are not failures.

#111772 forwards --s3-storage / --encrypted-storage in upgrade_runner.sh so the storage skip tags
actually fire in upgrade mode. Its merge commit 072f21d03ff164 is NOT an ancestor of this head
(git merge-base --is-ancestor 072f21d03ff164 bf0282985975 is false), and this head's check ran
13:04 UTC against a base predating the 09:13 UTC merge, so a master merge picks it up. The companion
source-side pin for the Stress-check variant is #111922 (ours, open).

Session id: cron:our-pr-ci-monitor:20260727-170000

…EFRESH permit

`StreamingBackgroundControl::claimCycle` read `isBlocked` a second time after
`++last_seen_refresh_epoch`, so a `SYSTEM START` landing in that gap reported
`claimed_blocked_refresh == false` even though the permit had been consumed on a
stopped table - `StorageRabbitMQ::threadFunc` then ran an ordinary cycle and the
one out-of-order cycle the `SYSTEM REFRESH` was entitled to was wasted on an
empty poll, which is exactly the bug this pull request fixes.

Take a single `isBlocked` sample at the top of `claimCycle` and decide both the
admission and the out-parameter from it. This closes the race in both
directions: a `STOP`/`PAUSE` arriving after an ordinary admission still cannot
retroactively turn that cycle into a refresh cycle, and a `START` arriving after
a blocked-refresh claim can no longer drop the self-driving path.
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed b4cef25effe:

  1. Addressed the Request changes blocker (StreamingBackgroundControl.h:69, commit 97e69511950). claimCycle no longer re-reads isBlocked after ++last_seen_refresh_epoch; it takes a single sample at the top of the function and decides both the admission and claimed_blocked_refresh from it. This closes the SYSTEM START-in-the-gap direction the bot flagged (permit consumed on a stopped table but the self-driving path dropped, wasting the permit) while keeping the original STOP/PAUSE-in-the-gap direction closed (an ordinary admission cannot be retroactively promoted into a refresh cycle). The inline thread is resolved.
  2. Merged master — picks up Upgrade check: honor storage skip tags by forwarding --s3-storage / --encrypted-storage #111772 (merged 2026-07-27 09:13 UTC, commit 072f21d03ff164), the owner of the only red, Upgrade check (amd_release) / t_plt_evict_reinsert (known issue Stress tests: Cannot start clickhouse-server — corrupted txn_version.txt of fabricated parts from 04241_part_loading_tree_rollback_* tests #111053). Clean merge; the diff versus master is still exactly the same 8 files.

Built all six translation units that use claimCycle (StorageRabbitMQ, RabbitMQSource, StorageKafka, StorageKafka2, StorageNATS, StorageObjectStorageQueue) after both the fix and the merge — clean, no warnings.

Note that alexey-milovidovs approval predates these commits.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 84/108 (77.78%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b4cef25

CI has fully finished on this head: 174 check-runs, 0 queued, 0 in progress, Finish Workflow success
at 11:25:22Z. Zero failing checks (153 success, 21 skipped), so there is nothing to assign an owner to.

Check / test Reason Owner / fixing PR
(none) - no failures on this head

The previous head bf0282985975 had one red, Upgrade check (amd_release) / t_plt_evict_reinsert
(fabricated txn_version.txt, issue #111053). It is green here because the master merge in this head
brought in the merged fix 072f21d03ff164, exactly as that ledger predicted under rule 3c.

One thing worth stating so it is not misread as a failure: CIDB shows 20 FAIL rows for
test_storage_rabbitmq/test_system_stop.py under Bugfix validation (integration tests, amd64) and
(aarch64). Both jobs are success. Those rows are the master-binary side of the bugfix validator,
which is required to fail there and pass with the PR build, so they are the check working as designed.

Session id: cron:our-pr-ci-monitor:20260728-120000

@PedroTadim

Copy link
Copy Markdown
Member

Backporting to fix CI

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 5, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 5, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 5, 2026
Backport #111480 to 26.7: Fix SYSTEM REFRESH on a stopped RabbitMQ table not consuming the backlog
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 9, 2026
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.7-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants