Repository navigation
Recover a NATS JetStream subscription closed by the broker - #112828
alexey-milovidov merged 14 commits into
Conversation
A NATS engine table reading from a JetStream stream stops consuming permanently once the NATS server is restarted. Nothing is logged, the connection reports healthy, and only DETACH TABLE plus ATTACH TABLE or a server restart recovers it. An asynchronous pull subscription renews its pull request only when a message is delivered: js_maybeFetchMore is reachable from the initial subscribe and from the two dispatch loops, and has no references in conn.c. A reconnect resends the SUB line but not the outstanding pull request, whose only other home was the server's waiting-request queue. So with nothing in flight when the server goes away, the chain never restarts. The server does report this. On shutdown it answers the outstanding request with 409 Server Shutdown, which the client maps to NATS_LIMIT_REACHED and turns into natsSubscription_Unsubscribe, so the local subscription is closed. ClickHouse missed it because isSubscribed only tests whether the subscription vector is non-empty, so subscribe() early-returned and the existing recovery path re-subscribed nothing. Add a per-subscription liveness check and consult it in the streaming task, which drops the subscriptions so the existing re-subscribe runs in the same iteration. Only JetStream consumers opt in: core NATS subscriptions are restored by the client already, and recovery drops buffered messages that core NATS never redelivers. A broker loss that leaves the subscription with no fetch status at all, such as a hard kill or a network partition, is not covered here. That needs a local fetch timeout, which would also tear down healthy subscriptions periodically, so it is left out. Updating the vendored client does not help. Upstream v3.13.0 still has no js_maybeFetchMore reference in conn.c.
The two churn guards counted matches inside a fixed 10000-line tail of the server log and asserted the count had not grown. At the log rate these tests produce, that window moves during the very interval each guard observes, so an older match scrolling out cancels a new one arriving and the assertion holds while the property it states is violated. The tests perform a restart shortly before measuring, which puts such an older match in the window by construction. Add log_line_count and count_in_log_after and assert exactly zero new lines after an absolute offset. count_in_recent_log is left alone: wait_for_streaming_started wants a fresh occurrence rather than an absolute count, which the moving window answers correctly. Measured on a build emitting the line about twice per observation window: the old assertion passed 8 of 8 while the new one failed 8 of 8, with the old count falling by several hundred as the tail scrolled. The new form reports the exact number of new lines instead of a difference. An absolute offset only goes stale if the log rotates between the anchor and the count, which is hours away at 1000M per file, and each guard asserts the log has not shrunk below its anchor so a rotation fails loudly.
Internal second-model review (2 rounds, 0 blockers outstanding)This change was reviewed independently of its author across two rounds: a cold code Round 2 (current head)
Both the cold review and the second model raised this one finding independently, It is not fixed here because the obvious remedy is not free. Asserting the message Round 1
The first is fixed. The counters are now anchored to an absolute log offset, so zero The second was declined. Its stated consequence is that unchanged code could pass, What was checked beyond the diffSubscription lifetime and the vendored client paths that close a pull subscription; Session id: cron:clickhouse-review-slot-50:20260731-214900 |
Pre-PR validation gate
Mutation testing, each built separately with the binary identity confirmed to change, then restored:
After every mutation the source was restored and verified by checksum, and the shipped tree contains no mutation residue. The two churn guards count matches after an absolute log offset rather than inside a fixed tail of the log, so a count of zero means no such line was written. A fixed tail moves as the instance logs, which lets an older match scroll out and cancel a new one arriving; on a build emitting the line twice per observation window the tail-based assertion passed 8 of 8 runs while the offset-based one failed 8 of 8. Regression sweep over the whole NATS suite, identical collected set in both arms: 0 verified regressions and 0 claimed improvements. Sixteen of the nineteen errors on the fix arm never started, dying in fixture setup with Not covered by this change: a broker loss that leaves the subscription with no fetch status at all, such as a hard kill or a network partition. A local fetch timeout would be needed, which brings a periodic teardown of healthy subscriptions, so it is deliberately out of scope here. |
|
cc @kssenii @antaljanosbenjamin, could you review this? A JetStream pull subscription renews its pull request only when a message is delivered, and a reconnect resends the SUB line but not the outstanding request, so a NATS table stops consuming permanently after a broker restart; |
|
Workflow [PR], commit [7bfd220] Summary: ✅
AI ReviewSummaryThis PR teaches Findings❌ [src/Storages/NATS/StorageNATS.cpp:670-673, src/Storages/NATS/INATSConsumer.cpp:74-80] [dismissed by author -- https://github.com//pull/112828#discussion_r3696320085] Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 29/30 (96.67%) · Uncovered code |
The two resumes-consuming tests were flaky in the integration flaky check (each failed 1 of 3 repeats under ASAN+UBSAN, on different workers). The server logs show why. Recovery is asynchronous: a closure queued while the broker was still restoring its streams can re-subscribe after the probe was already consumed, leaving a fresh subscription whose pull request has not been parked yet. Both failures killed the broker 30 ms and 43 ms after such a re-subscribe, so the request was never answered and the table was left with a subscription it has no status for. That is the residual this branch documents as out of scope, not the window under test. Every passing repeat had that gap two orders of magnitude wider. Consuming the probe proves a request was parked at some earlier point, but not that it still is when the broker goes down. Read `num_waiting` off the consumer immediately before the kill instead, so the precondition holds at that instant whatever recovery did in between. Test-only, and it does not weaken any arm: against the pristine master binary the same hardened tests still fail 9 of 12 (the three restart tests in every repeat), while the churn guard passes by design because it asserts an absence.
|
The integration flaky check was red on my own two new restart tests, so this is a fix in Each of the two failed 1 of 3 repeats under ASAN+UBSAN, on different xdist workers. The That request was never answered, so the table was left holding a subscription with no Consuming the probe proves a pull request was parked at some earlier point, but not that it It does not weaken any arm. Against the pristine master binary the same hardened tests still One other thing came out of my own review of this push, and I would rather record it than |
The two broker-restart tests each failed one of the flaky check's three repeats. Read off the server log at millisecond resolution, both failures had the same shape: the probe message published by `_restart_nats` was consumed, which exhausts the asynchronous pull request, so the client closed the subscription and recovery re-subscribed 0.5 s later; the kill then landed 14 ms after that fresh subscription, before its request was parked. The broker died without answering it, so nothing ever reported the subscription as closed, `needsResubscribe` stayed false, and consumption never resumed - the residual this pull request documents as out of scope, reached by the test's own probe rather than by the hard kill or partition it is meant to describe. In every passing repeat that gap was 0.5 s to 2.7 s instead, two orders of magnitude wider. A settle window cannot close this: the streaming task reschedules every 500 ms, so a re-subscribe can land between the last observation and the kill however long it has been quiet. Measured - a five second settle guard still let a failure through, with all eleven of its windows reporting no recovery at all. Drop the probe instead. A pull request is parked as soon as the subscription is created, so `num_waiting` establishes the precondition on its own, and nothing consumes, so nothing schedules a re-subscribe for the kill to race. Verified with the threshold mutated to an unreachable value: the wait then fails reporting `num_waiting is 1`, which both proves the wait is not vacuous and confirms a request is parked with no probe at all. Sixteen local runs of the four restart-family tests pass; against the pristine master binary the same tests still fail nine of twelve, matching the previous arm exactly, so no arm of the mutation matrix was weakened.
The previous commit said delivering a message exhausts the asynchronous pull request. That is wrong: `fetch->opts.FetchSize` defaults to `NATS_DEFAULT_ASYNC_FETCH_SIZE`, which is 128 (`js.h:31`, applied at `js.c:3050`), and the tests publish ten messages, so the request stays outstanding. What closes the subscription is a status message from the broker - `js_checkFetchedMsg` maps one to a non-OK `fetchStatus` (`js.c:1771-1800`) and `dispatch.c:317` then stores it, which is what our `hasClosedSubscription` observes. The fix and its measurements are unaffected: publishing still causes the closure, just by making the broker answer the parked request rather than by filling a batch. Only the stated reason changes.
Every assertion on `RESUBSCRIBE_LOG_LINE` expected zero matches, so rewording the message it looks for would leave both churn guards passing on a literal nothing emits. The settle test performs a restart and must therefore recover through that line, so assert it does, anchored to an offset taken before the restart. Verified by replacing the constant with a literal the server never writes: the control then fails with `assert 0 > 0`, where before it was the guards that were silently satisfied. Also drop the claim about what closes the subscription. Delivery does not exhaust the request and answering it does not close the subscription: it provokes a further pull request through `js_maybeFetchMore` (`dispatch.c:379`), and that request draws the non-OK status which `dispatch.c:317` stores. Publishing does precede the re-subscribe, which is what was measured, so the comment now says only that.
The wait helper still carried the wording corrected in the previous two commits. The default asynchronous fetch requests 128 messages while these tests publish ten, so a delivery leaves the request outstanding. Say only what the helper does: it observes the parked request without publishing.
Removing the probe was not enough. Draining the backlog to reach the idle state is itself followed by a re-subscribe at an unpredictable delay, so a restart can still land in the milliseconds before that subscription parks its request - measured again at 25.8 ms, with the same permanent silence afterwards. `num_waiting` cannot exclude it, because it counts parked requests broker side without saying which subscription parked them, so it reads one for the previous request while the fresh subscription has none. No check before the restart can close that gap, so detect it after. A re-subscribe logs before it can park a request, so a subscribe line written between the parked-request check and the restart marks a restart that never exercised the recovery, and that attempt is retried. Every measured failure has such a line within tens of milliseconds of the restart; no passing run has one. This cannot mask the bug. Against the pristine master binary the tests still fail on the consumption assertion, twice out of two, and the retry does not fire there at all, so a restart with recovery absent is still a valid trial. Forcing the check to report a race exercises the retry and then fails with `every one of 4 restarts raced a re-subscribe`, so a helper that silently retried forever could not pass unnoticed either.
The retry's window opened only after `_wait_for_parked_pull_request` returned, yet the reason it exists is that `num_waiting` can be satisfied by the previous request while a re-subscribe is already under way. A subscribe line written during the poll therefore fell outside the window and the raced restart counted as a trial. Anchor before the wait instead. The wider window is not cosmetic: under load it rejects restarts the narrow one accepted, three in one run against none in twelve, while sixteen runs on an unloaded host still pass with no retries at all.
Flaky check on
|
| if (consumers_ready && consumersNeedResubscribe()) | ||
| { | ||
| LOG_INFO(log, "A subscription was closed by the NATS server, resubscribing"); | ||
| unsubscribeConsumers(); |
There was a problem hiding this comment.
This makes ordinary JetStream restart recovery tear down all subscriptions as soon as one of them reports closed. That is unsafe once the table has another live subscription: subscribeImpl creates one natsSubscription per configured subject, so nats_subjects = 'a,b' is enough to reach a mixed closed/live state here. INATSConsumer::unsubscribe then drains the live sibling via natsSubscription_DrainTimeout, and in the vendored client that path locks conn -> sub (conn.c:3151-3204, sub.c:936-945), while async pull renewal does sub -> conn (js.c:2930-2938, pub.c:86). If a sibling renews while this recovery path is draining it, the streaming task deadlocks instead of recovering.
We need a recovery path that avoids draining still-live siblings here, for example by recovering only the closed subscription or consumer set, otherwise a multi-subject JetStream table can hang after the very broker restart this PR is supposed to fix.
There was a problem hiding this comment.
The cycle is real and I agree the recovery path should not be what drains a live sibling. I tried the narrowing you ask for and reverted it, because it strands a subject. Details, since the second half is the interesting part.
Re-derived all four links rather than citing the earlier round: natsConn_unsubscribe holds natsConn_Lock from conn.c:3151 into natsSub_startDrain at :3204, which takes natsSub_Lock at sub.c:936; js_maybeFetchMore holds nats_lockSubAndDispatcher from js.c:2930 across _sendPullRequest at :2938, reaching natsConn_Lock at pub.c:86. The !draining guard at dispatch.c:377 reads draining at :229, before natsSub_drain sets it at sub.c:797, so it does not close the window.
One correction to the mechanism: the mixed closed/live state is sufficient but not necessary, and the inversion is not a property of draining. On the non-drain path natsConn_unsubscribe reaches natsConn_removeSubscription at conn.c:3178, which calls natsSub_close (conn.c:3006), which takes nats_lockSubAndDispatcher at sub.c:252 under the same connection lock. natsSubscription_Destroy also unsubscribes any not-yet-closed subscription (sub.c:1336-1362). So the order is entered by any teardown of a still-valid subscription, and the already-closed short circuit at conn.c:3162 is what spares the closed ones. In the flaky-check job for the previous head, 229 subscriptions were created and 153 teardowns logged that short circuit, so of the order of 76 teardowns took the branch on a subscription the client still held valid, all on single-subject tables. That is why unsubscribeConsumers already reaches it on master through SYSTEM STOP and shutdown, with five callers on the merge-base before this PR added a sixth.
On the narrowing itself: requiring every subscription of the consumer to be closed does remove this occasion, and I implemented and tested it. It also introduces a worse failure. The dispatcher drains a single subscription on its own when that fetch draws a non-OK status (dispatch.c:377-383), and jsi->fetch is per subscription, so a partially closed consumer is reachable without any broker restart. With an all-closed condition that consumer is never torn down and the closed subject stays silent permanently, instead of recovering. Trading a lock-order hazard for a guaranteed stranded subject is not a good trade, so I reverted it. Recovering only the affected subscription is the shape that avoids both, but subscribe early-returns on a non-empty vector and subscribeImpl replaces the vector wholesale, so it is a real change rather than a tweak, and it cannot be verified in a test-only round.
What I did keep is a multi-subject restart test, which nothing covered before: a table on two subjects, restarted, then both subjects asserted to resume. Against a binary whose recovery never fires it fails on the consumption assertion in every repeat. It does not pin a mixed closed/live state, which needs a way to close one subject's subscription while its sibling stays valid, and that belongs with the per-subscription work.
So the deferral stands for the lock order and for mixed-state coverage, and I will link the fix here when it opens. The measurements are on the pushed head.
Recovery fired as soon as any subscription of a consumer reported closed. Teardown is per consumer, so with more than one subject that drained a still-live sibling, and in the vendored client draining takes the connection lock before the subscription lock (conn.c:3151 into natsSub_startDrain at :3204, sub.c:936) while asynchronous pull renewal takes them the other way round (js.c:2930 across _sendPullRequest at :2938, pub.c:86). Waiting for all of them removes that occasion: a restart terminates every fetch, so all-closed is the steady state and the mixed state is a transient the streaming loop re-evaluates every RESCHEDULE_MS. Single-subject tables, which is every existing test and the reported bug, are unaffected: over a one-element range the two predicates are identical, which is why the new multi-subject test is what covers this. Against a binary whose recovery never fires it fails on the consumption assertion in every repeat. The lock inversion itself is untouched and reachable on master without this path, since shutdown and SYSTEM STOP already tear down live subscriptions the same way.
Requiring all of them to be closed strands a subject instead. The dispatcher drains a single subscription on its own when that fetch draws a non-OK status (dispatch.c:377-383), and each subject has its own fetch, so a partially closed consumer is a state the client reaches without a broker restart. Waiting for the rest would then never re-subscribe the closed one and that subject would stay silent for good, which is worse than what it was meant to avoid. The multi-subject test added alongside it is kept: it passes here and covers the restart path for more than one subject, which nothing did before.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 28/30 (93.33%) · Uncovered code |
CI finish ledger - 23cdda4Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260802-020000 |
|
Correcting my own reply above on two points, after re-deriving this on current master ( The sibling framing does not close the cycle. An ABBA deadlock needs the same two lock objects contended in opposite orders. Arm A holds Upstream already fixed the cycle, and this fork predates the fix. nats-io/nats.c GH-823 describes arm B verbatim, citing the same So the remedy is a contrib pin refresh, not the ClickHouse-side teardown narrowing I proposed. I am not pursuing either here: across 90 days there are 0 NATS failures carrying a hang signature (0 of 380 FAILs match |
|
@groeneai, |
Picks up ef9be38 (ClickHouse#113571, 'Fix flaky test_keeper_dynamic_log_level'), which was the sole remaining red on this branch's CI and is unrelated to this change.
|
Branch updated: merged master The merge adds no changes of mine (identical patch-id vs the previous head, no submodule pin movement); CI is rerunning. |
|
|
||
| nats_helpers.kill_nats(nats_cluster) | ||
| time.sleep(4) | ||
| resubscribed = nats_helpers.count_in_log_after(instance, SUBSCRIBED_LOG_LINE, anchor) |
There was a problem hiding this comment.
The retry oracle here only treats Subscribed to subject test_subject as evidence that the restart raced a re-subscribe. That works for the single-subject tests, but test_nats_jet_stream_resumes_consuming_multiple_subjects_after_broker_restart reuses the same helper with nats_subjects = 'test_subject,right_insert1'.
If right_insert1 is the subscription that re-subscribed between the parked-request check and docker stop, _restart_nats will still count that restart as a valid trial even though it is exactly the uncovered “fresh subscription with no parked request” residual. That makes the new multi-subject test flaky against behavior this PR explicitly says it does not fix, so it is not stable evidence for the multi-subject recovery claim. The helper needs to watch every configured subject, or at least any Subscribed to subject ... line emitted by the consumer under test.
There was a problem hiding this comment.
right_insert1 cannot re-subscribe on its own, so the watched line is never missed.
subscribeImpl subscribes to every subject in one loop and logs one line per subject (NATSJetStreamConsumer.cpp:65-68); subscribeToSubject has that single call site. subscribe() returns early while isSubscribed() (INATSConsumer.cpp:58-66, :49), so a subscription vector is never topped up partially, and recovery is whole-consumer: unsubscribeConsumers() clears all subscriptions and the next cycle rebuilds them all (StorageNATS.cpp:670-674, :373).
Measured on this module's server log: Subscribed to subject test_subject 8, right_insert1 8, all 8 pairs adjacent, test_subject first in 8 of 8 with a 0.97 to 1.45 ms gap. It is first because nats_subjects is parsed order-preserving (StorageNATS.cpp:106, :203-213) and it leads the setting in all five restart tests. So watching every subject would not change any detection outcome.
Not changing the helper. The uncovered residual is unchanged and still out of scope.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units11 translation units recompiled, 37 s compile time in total, 11 of them have a recent master baseline. |
CI finish ledger - 7bfd220No failure needs an owner on this head: The Session id: cron:our-pr-ci-monitor:20260813-073000 |
5f6d1cd
The residual this PR left out of scope is live on master, and the remaining fix is in
|
An asynchronous JetStream pull subscription asks for more messages only when
one is delivered, and when the NATS client reconnects it re-sends the `SUB`
line but not the pull request the broker was holding. A broker that goes away
without answering that request therefore leaves the table subscribed, holding a
subscription that still looks healthy, and permanently silent.
`test_nats_restore_failed_connection_without_losses_on_write` hits this when
the consumer is still behind at the moment the broker is stopped: every message
was published and acknowledged into the stream, but the ones not yet delivered
are never fetched again, so the view stays short of the 100000 keys inserted:
AssertionError: ClickHouse lost some messages: 92807
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c260929910ea94be9a359bb69bf5e33d7b3a40e4&name_0=MasterCI&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%204%2F4%29
Recovery so far keyed only on a subscription the client had closed, which is
what a graceful shutdown produces by answering the outstanding pull request.
Report a reconnect as well, by comparing the reconnect count the client keeps
for the connection against the one taken when we subscribed, and re-subscribe
through the same path. Only JetStream consumers do this: a core NATS
subscription really is restored by the `SUB` line, and re-subscribing it would
drop buffered messages nothing redelivers.
The window this leaves uncovered was the residual documented in ClickHouse#112828, so
`_restart_nats` no longer has to retry until a restart lands outside it. A new
test reaches that state deterministically with `SIGKILL`, which answers nothing
and so has no subscription reported as closed to fall back on.
Related: ClickHouse#112828
Co-Authored-By: Claude Fable 5 <[email protected]>
Closes: #96651
Related: #103557
Related: #112464
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a
NATStable withnats_streamset silently consuming nothing after the NATS server is restarted. TheJetStreamsubscription is now re-established automatically instead of requiringDETACH TABLEandATTACH TABLE.Description
A
NATSengine table reading from aJetStreamstream stops consuming permanently once the NATS server is restarted. Nothing is logged, the connection reports healthy, and onlyDETACH TABLEplusATTACH TABLEor a server restart recovers it. It is also how the flakytest_nats_restore_failed_connection_without_losses_on_writefails on master.Root cause: an asynchronous pull subscription renews its pull request only when a message is delivered, and a reconnect resends the
SUBline without the outstanding pull request, so with nothing in flight when the server goes away the chain never restarts. The server does report this, answering the outstanding request with409 Server Shutdown, and the client then closes the subscription. ClickHouse missed it becauseisSubscribedonly tests whether the subscription vector is non-empty, so the existing re-subscribe path was gated on a predicate that cannot see a dead subscription.This adds a per-subscription liveness check and consults it in the streaming task, which drops the subscriptions so the existing re-subscribe runs in the same iteration. Only
JetStreamconsumers opt in: core NATS subscriptions are already restored by the client, and recovery drops buffered messages core NATS never redelivers.Validated with five new integration tests. Three restart the broker and fail on master, 9 of 9 repeats, before passing after the change; a fourth asserts a healthy consumer never re-subscribes, so it passes either way and exists to bound the cost. The fifth covers a restart of a table reading two subjects, which nothing covered before. Not covered: a broker loss leaving the subscription with no status at all, such as a hard kill, a partition, or a loss coinciding with a re-subscribe. That needs a local fetch timeout, which would also periodically tear down healthy subscriptions.
#103557 targets the same defect from a connection-level reconnect counter, but no longer applies to this code and has no integration test. Close whichever you prefer.
Version info
26.8.1.1343(included in26.8and later)