Skip to content

Recover a NATS JetStream subscription closed by the broker - #112828

Merged
alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-nats-jetstream-reconnect-resubscribe
Aug 13, 2026
Merged

alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-nats-jetstream-reconnect-resubscribe

Conversation

@groeneai

@groeneai groeneai commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #96651
Related: #103557
Related: #112464

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):

Fixes a NATS table with nats_stream set silently consuming nothing after the NATS server is restarted. The JetStream subscription is now re-established automatically instead of requiring DETACH TABLE and ATTACH TABLE.

Description

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. It is also how the flaky test_nats_restore_failed_connection_without_losses_on_write fails on master.

Root cause: an asynchronous pull subscription renews its pull request only when a message is delivered, and a reconnect resends the SUB line 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 with 409 Server Shutdown, and the client then closes the subscription. ClickHouse missed it because isSubscribed only 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 JetStream consumers 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

  • Merged into: 26.8.1.1343 (included in 26.8 and later)

groeneai added 2 commits July 31, 2026 19:40
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 0 blockers outstanding)

This change was reviewed independently of its author across two rounds: a cold code
review plus a separate second-model pass each round, with findings adjudicated
against the recorded evidence. Round 1 bounced one major back for a fix; round 2 is
clean. Nothing below is outstanding.

Round 2 (current head)

Finding Severity Verdict
💡 The resubscribe log literal has no positive control: every use of the test-side constant is a zero-count assertion, so a future rewording of the production message would leave both churn guards trivially satisfied nit Noted, not blocking

Both the cold review and the second model raised this one finding independently,
with the same mechanism and the same suggested remedy, and both graded it a nit.
It is durability of coverage rather than present vacuity, and the present
non-vacuity is measured rather than argued: on a build that emits the message about
twice per observation window, both guards fail with the exact counts reported, and
they pass 12 of 12 on the real build.

It is not fixed here because the obvious remedy is not free. Asserting the message
appears at least once around a broker restart would pin behaviour that is not
invariant: the instance log for these tests contains a restart that recovered
through the ordinary subscribe path with no such message in between, because the
teardown path also clears the subscription. Prescribing that assertion risks
introducing a flaky test, which would be worse than the flake this PR fixes. A
correct positive control needs its own measurement, and is a reasonable follow-up.

Round 1

Finding Severity Verdict
⚠️ Both churn guards used a moving-window log oracle that cannot express "zero new lines" major Agreed, fixed in this PR
⚠️ The restart helpers ignore the exit status of docker stop and docker start, so a restart that never happened could let unchanged code pass major Disagreed, with evidence

The first is fixed. The counters are now anchored to an absolute log offset, so zero
means zero, with a guard that fails loudly if the log rotates under the anchor. The
replacement was shown to be strictly stronger rather than argued to be: on a build
emitting the message about twice per window, the old assertion passed in 8 of 8
saturated repeats while the count it compared fell by 200 to 1200 lines, and the new
assertion failed in every one.

The second was declined. Its stated consequence is that unchanged code could pass,
and that is refuted by the measurement the PR already rests on: the three restart
tests fail on unmodified master in 9 of 9 runs, with no recovery message logged. The
helpers are pre-existing and unchanged by this PR.

What was checked beyond the diff

Subscription lifetime and the vendored client paths that close a pull subscription;
lock ordering between the storage mutex and the client subscription lock, including
whether the message callback can run while holding either; the complete set of
consumer subclasses, to confirm core NATS cannot opt in; whether the recovery branch
can loop; and whether each new test fails when the change is reverted.

Session id: cron:clickhouse-review-slot-50:20260731-214900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Gate Answer
(a) Deterministic repro? Yes. Publish, let the backlog drain so the pull chain is idle, kill_nats / revive_nats, publish again. Pre-fix the second batch never arrives: 9 of 9 repeats of the three recovery tests fail on the shipped assertion. Not a "~1 percent" shape.
(b) Root cause explained? Yes. An asynchronous JetStream pull request is renewed only when a message is delivered (js_maybeFetchMore is reachable from js.c:3092 and from the two dispatch loops dispatch.c:379 / :544, and has 0 references in conn.c), while a reconnect resends only SUB / UNSUB (conn.c:1184-1186). With nothing in flight the chain never restarts. On shutdown the server answers the request 409 Server Shutdown, which the client maps to NATS_LIMIT_REACHED (js.c:1799-1804) and turns into natsSubscription_Unsubscribe (dispatch.c:311-326), so sub->closed becomes true. isSubscribed only tests !subscriptions.empty(), so the existing recovery was gated on a predicate that cannot see that.
(c) Fix matches root cause? Yes. It observes the closure the client already performs, per subscription, and reuses the existing unsubscribe and re-subscribe pair. No widened bound, no no-parallel, no retry-count bump, no reduced workload, no defensive guard at the symptom.
(d) Test intent preserved, new tests added? Yes. The existing 100000-message restore test is unchanged. Four tests are added: recovery after one restart, recovery after two restarts, a guard that a healthy consumer never re-subscribes, and a guard that recovery settles instead of firing every streaming cycle. The last two exist because both failure directions were real risks for this design family.
(e) Demonstrated in both directions? Yes. Fix arm 24 passed of 24 (4 tests x 6). Pre-fix arm on a pristine master build 9 failed of 12, every failure being the shipped assertion with 0 recovery log lines present. The fourth test passes pre-fix by design, since it asserts the absence of churn.
(f) General across code paths? Yes. js_PullSubscribeAsync has one call site in src/. Core NATS is gated deliberately (see below). The direct-read path is not a carrier: a viewless source sets unsubscribe_on_destroy and ~NATSSource unsubscribes, so every SELECT builds a fresh pull request. A consumer-leadership change on a multi-server setup terminates the fetch through the same dispatch path, so it is covered too.
(g) Generalizes across inputs? The predicate is a per-subscription boolean with no type or parameter surface. All three vector shapes are covered: empty reads as not-subscribed rather than dead, one subject, and many subjects (a JetStream consumer holds one subscription per subject).
(h) Backward compatible? Yes. No new setting, no default change, no format, serialization or protocol change, so no SettingsChangesHistory.cpp entry is required. Core NATS behaviour is byte-identical to master, because the base predicate returns false.
(i) Invariants and contracts preserved? Yes. consumers_mutex is held for the new read exactly as for the existing unsubscribe. Recovery reuses the existing unsubscribe and subscribe pair, so the receive queue is finished and reallocated. Unacked messages are redelivered at least once by JetStream, which is why the tests assert count(DISTINCT key). With Timeout and Heartbeat both zero no fetch timers exist, so none can leak across repeated recovery cycles.

Mutation testing, each built separately with the binary identity confirmed to change, then restored:

  • Reverting the liveness check to !subscriptions.empty() reddens the recovery tests (3 failed).
  • Reporting "alive" whenever the vector is non-empty reddens the same 3.
  • Inverting the predicate so a healthy subscription reads dead reddens both churn guards. It reddens them on their consumption assertion rather than on their churn count, because recovery then fires every streaming cycle and tears the subscription down before a message is consumed.
  • Emitting the recovery log line unconditionally, about twice per observation window, reddens both churn guards on the churn count itself, reporting 1 or 2 new lines against an expected zero. This is what shows those guards measure churn rather than only consumption.
  • Removing the core NATS gate is a proven no-op, so the gate is justified by source reasoning rather than by a test: every fetchStatus write is fetch-gated (dispatch.c:131, :146, :275) and :317 dereferences fetch unconditionally, so a core subscription, which has no jsi and therefore no fetch, cannot reach the closure branch. The gate still ships because it keeps core NATS byte-identical to master, whereas an ungated predicate could route the one core path that does close a subscription into dropBuffered, which core NATS never redelivers.

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 Connection refused while the host ran six competing test sessions; the same tests are green on the other arm, and no instance log contains a fatal or sanitizer line.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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; isSubscribed only tests that the subscription vector is non-empty, so it cannot see a subscription the client has already closed, and this adds a liveness check that the streaming task acts on.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7bfd220]

Summary: ✅


AI Review

Summary

This PR teaches NATS JetStream tables to notice when the client has already closed a pull subscription after a broker restart and to re-subscribe automatically. The narrow closed-subscription case is addressed, but I do not think the change is ready to merge yet: the new recovery path still tears down every JetStream subscription when any one closes, and on the pinned nats.c that can deadlock against a live subscription renewing its own pull request. The new multi-subject test also does not yet isolate itself from the residual restart race the PR explicitly leaves out of scope.

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] consumersNeedResubscribe recovers by calling unsubscribeConsumers() on the whole storage, so one closed JetStream subscription can still drain a different subscription that is valid and actively renewing. On the pinned nats.c, natsConn_unsubscribe takes the connection lock and then touches the subscription lock (natsSubscription_IsValid / natsSub_startDrain), while js_maybeFetchMore holds that same subscription lock and publishes the next pull request under the connection lock. If a live subscription renews while this new branch drains it, the two threads deadlock and the background streamer hangs instead of recovering. Suggested fix: do not drain still-valid JetStream subscriptions from this path; recover only the closed subscription or consumer set, or update the vendored nats.c pin before relying on all-consumers teardown.

Tests

⚠️ [tests/integration/test_storage_nats/test_nats_jet_stream.py:1059,1148] _restart_nats only treats Subscribed to subject test_subject as evidence that a restart raced a re-subscribe. In the new multi-subject test, a race on right_insert1 is still the uncovered “fresh subscription with no parked request” residual, but the helper will count that restart as a valid trial. Please make the retry oracle watch every configured subject, or any subscribe log for the consumer under test, so this test is evidence for the multi-subject contract instead of a flake against behavior the PR explicitly does not fix.

Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 29/30 (96.67%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 1, 2026
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.
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

The integration flaky check was red on my own two new restart tests, so this is a fix in
this PR rather than a pre-existing failure. Pushed ad382c133e1a51, test-only.

Each of the two failed 1 of 3 repeats under ASAN+UBSAN, on different xdist workers. The
server logs give the reason. Recovery is asynchronous, so a closure queued while the broker
was still restoring its streams can re-subscribe just after the probe message 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:

11:53:29.612  A subscription was closed by the NATS server, resubscribing
11:53:29.613  Subscribed to subject test_subject
11:53:29.642  Connection ... got disconnected from NATS server

That request was never answered, so the table was left holding a subscription with no
status. That is the residual this PR documents as out of scope, not the window under test.
For comparison, every passing repeat had that same gap between 0.5 s and 2.7 s, two orders
of magnitude wider.

Consuming the probe proves a pull request was parked at some earlier point, but not that it
still is when the broker goes down. The tests now read num_waiting off the consumer
immediately before the kill instead, so the precondition holds at that instant whatever
recovery did in between.

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. With the fix, 16 of 16 pass. I also checked the new wait is not
vacuous: forcing its threshold unreachable makes the test fail and report num_waiting is 1,
so it really does observe a parked request.

One other thing came out of my own review of this push, and I would rather record it than
leave it implicit. unsubscribeConsumers drains every consumer, and if one subscription is
closed while a sibling is still valid, draining the live one takes the client's connection
lock before its subscription lock (conn.c:3151 then sub.c:936), while an asynchronous
pull renewal takes them in the opposite order (js.c:2930 then pub.c:86). I have not
observed a hang, and it is bounded: an already-closed subscription short-circuits at
conn.c:3162 before the drain branch, so it needs a mixed-validity multi-consumer table. It
is also not introduced here, that function already has five callers on master including
SYSTEM STOP and shutdown. I am tracking it separately rather than widening this PR, and the
likely fix is to drop only the closed subscriptions instead of draining all of them.

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

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Flaky check on ad382c133e1a51, fixed in 7caf125cfc6dd3

test_nats_jet_stream_resumes_consuming_after_two_broker_restarts failed one of the flaky check's
three repeats. Read off the job's own per-repeat record, the two-restart test failed on gw1 only and
the single-restart test passed 3/3, so the previous round's guard did help but did not go far enough.

Root cause, from the server log at millisecond resolution: the probe message the test published to
prove a pull request was parked is itself followed by a re-subscribe, and the restart then landed
14 ms after that fresh subscription, before its request was parked. The broker died without answering
it, so nothing reported the subscription as closed and consumption never resumed. In all three passing
repeats that gap was 0.5 to 2.7 s instead. That is the window this pull request documents as out of
scope, reached by the test's own probe rather than by the hard kill or partition it describes.

The probe is gone: a pull request is parked as soon as the subscription is created, so num_waiting
establishes the precondition without publishing anything. Draining the backlog to reach the idle state
does the same thing though, so a restart can still race a re-subscribe. Since no check before the
restart can exclude that (a five second settle guard still let a failure through, with every one of its
windows reporting no recovery), it is detected afterwards: 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.

This cannot mask the defect. Against the pristine master binary the tests still fail on the
consumption assertion and the retry does not fire 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 retried forever could not pass
unnoticed either. Sixteen runs of the four restart-family tests pass on an unloaded host; against
pristine master the same tests fail nine of twelve, matching the earlier arm.

Two corrections for the record, both found in review: I had written that delivering a message
exhausts the pull request. It does not - the default asynchronous fetch requests 128 messages and
these tests publish ten. Delivery instead provokes a further pull request through js_maybeFetchMore,
and that request draws the non-OK status which closes the subscription. Separately, the retry's
window originally opened after the parked-request poll rather than before it, so a re-subscribe during
the poll was invisible to exactly the check meant to catch it.

The lock-ordering question raised on the earlier round is unchanged and still deliberately out of
scope for this test-only round; a fix task owns it, and its fixing-PR link will be posted here.

Session id: cron:clickhouse-maint-slot-12:20260801-144300

if (consumers_ready && consumersNeedResubscribe())
{
LOG_INFO(log, "A subscription was closed by the NATS server, resubscribing");
unsubscribeConsumers();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 28/30 (93.33%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 23cdda4

Every failure below has an owner: a fixing PR (mine 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
Integration tests (amd_tsan, 6/6) / test_nats_jet_stream_resumes_consuming_after_two_broker_restarts fixture defect in the test helper, not the recovery under test: _wait_for_parked_pull_request polls ConsumerInfo.num_waiting for 60 s and aborts with num_waiting is 0 BEFORE the restart is attempted, so no recovery behaviour is exercised. Distinct from the family's real consumption oracle (consumption did not resume, view holds N of M keys), which passed a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

Finish Workflow succeeded and all 174 check-runs completed. The Bugfix validation (integration tests, amd64/aarch64) rows that CIDB lists as failing are the expected-to-fail-on-master arm of
those jobs, which both concluded success, so they are not failures needing owners.

Session id: cron:our-pr-ci-monitor:20260802-020000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correcting my own reply above on two points, after re-deriving this on current master (e6cc65db16ddb0f, nats-io pin cf441828d30fdd5d).

The sibling framing does not close the cycle. An ABBA deadlock needs the same two lock objects contended in opposite orders. Arm A holds conn and wants sub_X; arm B holds sub_Y and wants conn. That closes only when sub_X == sub_Y, i.e. the subscription being torn down is the one renewing its own pull request. A sibling gives sub_Y != sub_X, so arm A's natsSub_Lock(sub_X) is not blocked by it. Both nats_subjects = 'a,b' and nats_num_consumers = 2 produce siblings, so neither is a carrier. The four links are traced correctly; the reachability argument built on them (mine included) is not.

Upstream already fixed the cycle, and this fork predates the fix. nats-io/nats.c GH-823 describes arm B verbatim, citing the same js.c:2929/2937/1841 and pub.c:86 lines. It was fixed by nats-io/nats.c#834 (merge 7220e9f6e081, 2025-02-03), which releases the sub+dispatcher lock before publishing and hoists the unlock in js_PullSubscribeAsync above the first js_maybeFetchMore. That breaks arm B, so the cycle is gone regardless of what teardown does. It is absent from our pin (grep -c _publishPullRequest src/js.c is 0, and js.c:2930-2944 still holds the lock across _sendPullRequest) and present in upstream main. Reason: ClickHouse/nats.c forked at 86fc47ff1b3cf (#822, 2024-11-24), 14 commits behind that fix and 276 behind main today.

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 deadlock/DrainTimeout/did not finish draining/Timeout!/hung, with controls confirming the filter discriminates: Error matches 156 of 176 non-empty contexts, and deadlock matches 72 rows fleet-wide over 30 days). The only live NATS failure family is message loss, not a hang. No user-reachable consequence observed, so I am not raising it as work.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, test_keeper_dynamic_log_level is fixed on master, please update the branch.

@alexey-milovidov alexey-milovidov self-assigned this Aug 13, 2026
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Branch updated: merged master 75bf16326ab6 in, so the build now includes #113571 (merged 2026-08-10, ef9be3874ac3) and test_keeper_dynamic_log_level should clear.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7bfd220a1 with master 75bf16326 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.20 MiB 689.20 MiB -3.01 MiB (-0.43%)

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 units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7bfd220

No failure needs an owner on this head: Finish Workflow = success and all 177 check-runs
completed with zero failures (156 success, 21 skipped).

The Bugfix validation (integration tests, amd64/aarch64) rows that a naive CIDB query lists as
failing are the expected-to-fail-on-master arm of those jobs; both checks concluded success, so
they are not failures needing owners.

Session id: cron:our-pr-ci-monitor:20260813-073000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into ClickHouse:master with commit 5f6d1cd Aug 13, 2026
358 of 359 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The residual this PR left out of scope is live on master, and the remaining fix is in ClickHouse/nats.c

test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write still fails
after this merged: 6 unrelated PRs since 2026-08-13 15:43Z (3444 OK), all
Integration tests (arm_binary, distributed plan, N/4), shortfalls 92459-97752 of 100000.

Root cause, from two failing runs. Not a slow drain: consumption stops dead. In
#113073 @ 1b089d3b
the recovery added here fires once at 18:31:21.506 and re-subscribes at .507 — then that connection
disconnects at .514, 7 ms later. After the reconnect: resubscribing 0, Subscribed to subject
0, Queues are empty 665 with Queues are not empty 0, and 0 parts written to the target table for
5.5 min. Same shape in #114802 (36 ms gap, 668/0).

The new subscription's pull request dies with that reconnect. _resendSubscriptions
(contrib/nats-io/src/conn.c:1113-1196) re-sends only the SUB line and never re-arms the pull
request, and the chain is renewed exclusively from js_maybeFetchMore on message delivery
(dispatch.c:379,544). So the subscription stays natsSubscription_IsValid — teardown confirms it,
taking the normal path, not the "already closed" one — and needsResubscribe() is false forever.
For users: a JetStream table whose broker restarts or fails over at the wrong moment stops ingesting
permanently and silently. Same class as #96651.

Why I am not sending a patch. I designed four detectors and all are refuted, each in-tree:

  • jsOptions.PullSubscribeAsync.Heartbeat - the server rejects it. nextReqFromMsg requires
    heartbeat*2 <= expires; js.c:2921-2922 sets expires only when Timeout != 0, which
    ClickHouse leaves 0. Adding Timeout is not a repair: it bounds the fetch lifetime, so healthy
    subscriptions are torn down on a schedule, and expires decays (startTimeMillis set once at
    js.c:3045, recomputed at :2922) until the same reject returns.
  • natsConnection_GetStats reconnect counter - deadlock. GetStats takes conn then subsMu
    (conn.c:3910); processMsg takes subsMu then the subscription (:2709); js_maybeFetchMore
    takes the subscription then publishes under conn (js.c:2930,2938). A wrapper mutex is not on
    that cycle.
  • any counter seeded around subscribeConsumers() - two background callers race it
    (:296 and :687), and subscribe() early-returns when already subscribed, so the second caller
    retires the reconnect being recovered.
  • any trigger in threadFunc - incomplete. With no materialized view initializeConsumersFunc
    returns at :288 and never starts the streaming task, while NATSSource::generateImpl subscribes
    directly (NATSSource.cpp:110-120), so a plain SELECT gets a subscription that loop never sees.

The fix belongs where the request is lost: re-arm the JetStream pull request in
_resendSubscriptions. That is ClickHouse/nats.c, a separate repo I have no push access to, and it
changes locking and lifetime semantics of a vendored client for every NATS user, so it is not mine to
decide. The options are to patch the fork, upstream it, accept a narrower fix knowing it carries the
coverage gap and deadlock risk above, or leave it - this PR already covers the common case.

Happy to write whichever you prefer. Not opening a PR meanwhile.

Full evidence, including the refuted designs with file:line, is in my task notes; I can paste any
part of it here.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 6, 2026
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]>
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

NATS JetStream pull consumer does not recover after failover (or change server)

5 participants