Skip to content

Revert "Revert "Resume a NATS JetStream subscription after a reconnect"" - #119301

Merged
alexey-milovidov merged 12 commits into
masterfrom
revert-119270-revert-nats-jetstream-reconnect-resume
Oct 7, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
revert-119270-revert-nats-jetstream-reconnect-resume

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Reverts #119270


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

Version info

  • Merged into: 26.10.1.1722-master (included in 26.10 and later)

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aa851ad]

Summary: ✅


AI Review

Summary

This PR re-applies the JetStream reconnect-resume work and follows through on the tricky ownership edges around direct SELECT, skipped broken messages, and SYSTEM STOP / view-detach handoff. I read the current diff and the prior review threads, and the remaining code now matches the intended contracts; I did not find a new correctness, safety, or performance issue that warrants another inline finding.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit aa851ad.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 204/221 (92.31%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 10, 2026
Comment thread src/Storages/NATS/NATSSource.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing aa851ad14 with master b3916c57c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 915744a54; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

13 object files changed (+43.17 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/NATS/NATSSource.cpp.o 140.94 KiB 160.71 KiB +19.77 KiB (+14.02%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

17 translation units recompiled, 39 s compile time in total, 17 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: b570523c-eecf-4e0b-8632-a83d595baddc
  • MIRAI run: f8056e2c-f5b3-417c-a1ad-d13639e7aaaf
  • PR check IDs:
    • clickbench_3333800_1791196728
    • clickbench_3333813_1791196728
    • clickbench_3333819_1791196728
    • tpch_adapted_1_official_3333826_1791196728
    • tpch_adapted_1_official_3333856_1791196728
    • tpch_adapted_1_official_3333870_1791196728

alexey-milovidov and others added 2 commits September 19, 2026 12:27
A direct `SELECT` that finds its consumer unsubscribed subscribes it itself
and unsubscribes it again in `~NATSSource`. `StorageNATS::read` gives each of
those sources `max_block_size = 1` while `NATSJetStreamConsumer::subscribeToSubject`
leaves the pull subscription with unbounded pending limits, so the query can
return its first row with the rest of the pulled batch already in the local
queue. `dropConsumed` only released the handles of what the query had read, and
`unsubscribe` then destroyed the subscription those buffered messages arrived
on, so the broker kept counting them as delivered until the ACK deadline and
neither the next query nor a view attached right afterwards could see them.

The `unsubscribe_on_destroy` path now goes through
`finishAndReturnUnprocessed(ReturnToBroker)` before `unsubscribe`, like every
other place that parts with a subscription. `ReturnToBroker` is right for both
sets: by the time the destructor runs, `generate` has acknowledged what the
query committed, so whatever is left owes its rows to nothing. A background
streaming source still only calls `dropConsumed`: it stays subscribed and the
next cycle keeps consuming from the same local queue.

New test `test_nats_jet_stream_direct_select_hands_back_the_backlog_it_did_not_read`:
publish 500 messages with no view attached, run one direct `SELECT`, then attach
a materialized view and require all 500 keys with `ack_wait = 600`. On a control
binary without the fix the view holds 0 of 500 after two minutes; with the fix
the test passes in 24 s.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Storages/NATS/NATSSource.cpp Resolved
Comment thread src/Storages/NATS/INATSConsumer.h Resolved
Comment thread src/Storages/NATS/INATSConsumer.cpp Resolved
Comment thread src/Storages/NATS/INATSConsumer.h Outdated
Comment on lines +154 to +156
/// Reconnect count of the connection as of the moment we subscribed. Only ever touched under the
/// storage's consumers mutex, together with `subscriptions`.
UInt64 connection_reconnect_count = 0;

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.

This smells like a bad construction: this counter is protected by a mutex outside of the class? That is wrong.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Agreed, the comment described it wrongly. No mutex protects it: apart from the received-message queue (which the NATS client thread fills, and which has its own lock), a consumer has exactly one owner at a time. That is the storage while the consumer is in the pool, or the source that took it out with popConsumer until it gives it back with pushConsumer; the hand-off under consumers_mutex gives the happens-before. connection_reconnect_count follows the same rule as subscriptions, consumed_messages and the rest of the consumer state. In b5b2f89 the class now documents that single-owner model, and the misleading per-field remark is gone. Making just this one field atomic would suggest the consumer is safe for concurrent use, and it is not.

Comment thread src/Storages/NATS/NATSSource.cpp Resolved
{
LOG_INFO(log, "A subscription stopped consuming from the NATS server, resubscribing within a running query");
consumer->finishAndReturnUnprocessed(
background_streaming ? INATSConsumer::SkippedMessages::Acknowledge

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.

We ack some messages on SELECT (see generate) but not the skipped messages? this looks bad. What is the reaosn?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 A direct SELECT acknowledges skipped messages at the same point as everything else it read: ackConsumed acknowledges both consumed_messages and skipped_messages, and generate calls it only at the commit point (the final empty chunk, with nats_commit_on_select, when the query was not cancelled). The spot you point at is the in-query recovery, which runs long before that commit point. If it acknowledged the skipped message there, a query cancelled afterwards would still have consumed a message it never committed, against the nats_commit_on_select contract. So there the message goes back to the broker like everything else the query holds. It is redelivered at once, skipped again, and acknowledged together with the rest when the query commits. Only a streaming cycle acknowledges it during recovery, because it never inserts a skipped message, so its skip is already final. The comment now says this in two lines (b5b2f89).

Comment thread src/Storages/NATS/NATSSource.cpp Resolved
alexey-milovidov and others added 4 commits September 27, 2026 06:27
…resubscribe, shorten comments

- `~NATSSource`: a direct `SELECT` that took a consumer the streaming task
  had subscribed now returns the messages it read but did not commit to the
  broker (`INATSConsumer::returnConsumed`) instead of destroying their
  handles, which hid them until the ACK deadline. The hand-off test now
  runs such a `SELECT` before attaching the view again.
- `NATSSource::generateImpl`: if resubscribing a consumer the streaming task
  owns throws, mark the storage consumers not ready so that
  `subscribeConsumers` subscribes it again, the same way
  `resubscribeStaleConsumers` does; a streaming cycle lets its other sources
  finish, a direct `SELECT` rethrows.
- Add `INATSConsumer::nackMessages` next to `ackMessages`.
- Document the single-owner model of `INATSConsumer` instead of claiming
  that `connection_reconnect_count` is protected by the storage's mutex.
- Shorten the long comments.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…_not_return_stale_copies`

The test came from master and assumed that a direct `SELECT` leaves what it
did not read stuck at the broker until `ack_wait`, so any row a later read
returned had to be a stale local copy. This PR returns those messages to the
broker when the read ends, so the broker legitimately redelivers them to the
next read (it failed in every integration job: `assert 3 == 0`). Check
instead that each later read returns no more rows than the broker delivered
while it ran, using `delivered.consumer_seq`, which counts redeliveries: a
stale local copy is a row without a delivery.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119301&sha=049bc966960503007e64405d745efe118e18b160&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20targeted%29
#119301

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The AI review asked for a focused test of the failure path fixed in
b5b2f89. A `ONCE` failpoint `nats_fail_resubscribe_within_query` makes
the in-query recovery fail right before `subscribe`. The new test
`test_nats_jet_stream_streaming_recovers_after_a_failed_in_source_resubscribe`
triggers that recovery mid-cycle with a broker hard kill, then requires every
row to reach the view with no consumer unsubscribed afterwards: the storage
subscribes the consumer again once and keeps it subscribed, instead of every
following cycle subscribing and unsubscribing it itself.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review's minimum required actions and the open threads:

  • A failed in-source resubscribe on a consumer the streaming task owns now marks the consumers not ready, so subscribeConsumers retries it (b5b2f89). Test: test_nats_jet_stream_streaming_recovers_after_a_failed_in_source_resubscribe, driven by the new ONCE failpoint nats_fail_resubscribe_within_query (a0a0e8c).
  • A direct SELECT that returns a still-subscribed consumer now NAKs what it read without committing (INATSConsumer::returnConsumed) (b5b2f89). test_nats_jet_stream_hands_back_the_backlog_of_a_consumer_a_direct_select_left_subscribed now runs such a SELECT before re-attaching the view.
  • The only CI red was test_system_stop.py::test_repeated_direct_reads_do_not_return_stale_copies (from master). It assumed a direct read leaves its leftovers pending at the broker, but this PR returns them. Its oracle now compares rows against delivered.consumer_seq, so it still catches stale local copies (13f0f4a).
  • Comments shortened throughout, and nackMessages added.
  • Merged master.

I could not run the integration tests locally this time: the host disk is full and Docker cannot start containers. The changed translation units compile.

alexey-milovidov and others added 2 commits October 3, 2026 17:44
# Conflicts:
#	src/Storages/NATS/StorageNATS.cpp
…t_return_stale_copies`

The delivery counter is global to the durable consumer, so a stale local copy
could hide behind a concurrent legitimate redelivery. Purging the stream once
the burst is delivered leaves the broker nothing to deliver, so any row a later
direct read returns can only be a stale buffered copy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/NATS/StorageNATS.cpp Resolved
alexey-milovidov and others added 2 commits October 5, 2026 07:48
… with no view

A direct `SELECT` that takes a consumer out of the pool while the last view is being
dropped hands it back still subscribed, and in the viewless state the engine runs
`initializeConsumersFunc`, which never looked at `SYSTEM STOP` / `SYSTEM PAUSE`. A stopped
table could therefore keep a subscription alive indefinitely. Now, while the table is
blocked, `initializeConsumersFunc` unsubscribes any consumer in the pool that is still
subscribed, returning its backlog to the broker.

Add `test_nats_jet_stream_stop_unsubscribes_a_consumer_a_direct_select_left_subscribed`,
sharing the setup with the existing test through a helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failures below and fix them in a separate PR. If a fix is already in progress, link it here. They are unrelated to this PR, which only touches the NATS engine:

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

All three already have a fixing PR:

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. Confirmed: CI on aa851ad (which includes master with #123632 and #123636) is fully green now, so none of these three failures remain on this PR. The two open review threads from @antaljanosbenjamin (single-owner model of the consumer state, and when a direct SELECT acknowledges skipped messages) have replies explaining the changes made in b5b2f89. They are waiting for the reviewer to confirm.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Oct 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit ddbc3d8 Oct 7, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the revert-119270-revert-nats-jetstream-reconnect-resume branch October 7, 2026 10:08
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). pr-not-for-changelog This PR should not be mentioned in the changelog 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.

4 participants