Skip to content

Fix a server crash on a NATS table whose credentials the broker rejects - #119853

Merged
alexey-milovidov merged 7 commits into
masterfrom
fix-nats-authorization-error-crash
Sep 14, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
fix-nats-authorization-error-crash

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Closes: #118449

A table with ENGINE = NATS took the whole server down with a segmentation fault when the broker
started rejecting its credentials - after a password rotation, or on an expired token, which
reports Authentication Expired and takes the same path as Authorization Violation.

The connection is configured for infinite reconnects, but the client library gives up and closes a
connection for good once it has seen the same authorization error on two consecutive reconnect
attempts (_processAuthError: "We want to do retries unless we get the same error again"). Closing
it crashed the shared event loop thread which serves every NATS table of the server:

BaseDaemon: Address: 0x10. Access: <not available>. Address not mapped to object.
BaseDaemon: 2. uv_close @ 0x000000001eb9b8d1
BaseDaemon: 3. uvAsyncCb(uv_async_s*) @ 0x000000001a17d678
BaseDaemon: 4. uv__async_io
BaseDaemon: 5. uv__io_poll
BaseDaemon: 6. uv_run
BaseDaemon: 7. DB::NATSHandler::runLoop()

_evStopPolling runs once per reconnect attempt and once more from _close when the library gives
up, because _close only checks nc->el.attached, which _evStopPolling does not clear. Each run
asks the libuv adapter to remove the write and then the read event, and the removal which brings
nle->events to zero closes the poll handle and sets nle->handle to NULL. Every further
removal then reached the unguarded uv_close((uv_handle_t*) nle->handle, ...) in uvPollUpdate,
and uv_close faulted reading the handle's type field at offset 0x10.

The submodule bump guards uvPollUpdate against a handle which is already gone, and stops asking a
connection which is not being polled to stop polling - _evStopPolling hands the socket close to
the adapter, which by then only knows the socket it was given when it was attached, so the second
run also leaked the socket of the last reconnect attempt.

Fixing only the crash would leave the table dead: nothing reopens a connection the client library
has closed, so after the rotation was rolled back the table would never consume again until a
DETACH/ATTACH. StorageNATS now notices a closed consumers connection and replaces it,
together with the consumers bound to it. It reports the closed connection under its own logger,
which carries the table name, with the last error the client library recorded on it - the library
keeps Authorization Violation on a connection it closed for good - so that an operator with
several NATS tables can tell whose credentials to fix:

StorageNATS (test.nats): The NATS client library closed the connection to cluster: [hidden] for good. Last error: Authorization Violation. Creating a new one

The asynchronous error handler of the client library is registered as well, so that the rejection
is logged when it happens instead of being printed to stderr by the library's default handler.

The new integration test drives a table through the rotation against a minimal broker which rejects
the credentials on demand - a real broker cannot be made to reject the credentials of a live
connection without being restarted with a different configuration. It reproduces the crash on
master and checks both halves of the fix: the server survives, and the table resumes consuming
once the credentials are accepted again.

The recovery path is shared with JetStream, whose half of the contract is different: replacing the
connection tears down the durable pull consumer's subscription with messages possibly still
unacknowledged, and the table has to resume through a fresh subscription to the same durable
consumer. That needs a real broker, so a second test puts an authentication proxy in front of the
JetStream-enabled nats1 broker, which rejects the credentials of the live table on demand, and
checks that the table drains the backlog exactly once, keeps consuming, leaves nothing pending
acknowledgement, and that messages delivered but unacknowledged when the connection was closed are
redelivered to the rebuilt consumer.

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fixed a crash of the server caused by a table with ENGINE = NATS whose credentials the broker started to reject, for example after a password rotation or on an expired token. Such a table now recreates its connection and resumes consuming once the credentials are accepted again, instead of staying silently idle.


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

Version info

  • Backported to: 26.8.5.10, 26.7.9.12, 26.6.7.15, 26.3.33.85

…ects

A table with `ENGINE = NATS` took the whole server down with a segmentation
fault once the broker started rejecting its credentials - after a password
rotation on the broker, or on an expired token, which reports
`Authentication Expired` and takes the same path as `Authorization Violation`.

The connection asks for infinite reconnects, but the client library gives up
and closes a connection for good after the same authorization error on two
consecutive reconnect attempts. Closing it crashed the event loop thread which
serves every `NATS` table of the server:

    BaseDaemon: Address: 0x10. Access: <not available>. Address not mapped to object.
    BaseDaemon: 2. uv_close
    BaseDaemon: 3. uvAsyncCb(uv_async_s*)
    BaseDaemon: 4. uv__async_io
    BaseDaemon: 5. uv__io_poll
    BaseDaemon: 6. uv_run
    BaseDaemon: 7. DB::NATSHandler::runLoop()

`_evStopPolling` runs once per reconnect attempt and once more from `_close`
when the library gives up, because `_close` only checks `nc->el.attached`,
which `_evStopPolling` does not clear. Each run asks the `libuv` adapter to
remove the write and then the read event, and the removal which brings
`nle->events` to zero closes the poll handle and sets `nle->handle` to `NULL`.
Every further removal then reached an unguarded
`uv_close((uv_handle_t*) nle->handle, ...)`, which faults on the handle's
flags field. The submodule bump guards the adapter against a handle which is
already gone and stops asking a connection which is not being polled to stop
polling, which also leaked the socket of the last reconnect attempt.

Fixing only the crash would leave the table dead: nothing reopens a connection
the client library has closed, so the table would never consume again until a
`DETACH`/`ATTACH`, even after the rotation was rolled back. `StorageNATS` now
replaces a closed consumers connection, together with the consumers bound to
it, and the asynchronous error and closed callbacks of the client library are
registered so that a rejected authentication is reported per table in the log
instead of being printed to `stderr` by the library's default handler.

Closes: #118449
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d00e52d]

Summary: ✅


AI Review

Summary

This PR fixes the NATS auth-rejection failure mode in two layers: the bundled libnats adapter no longer double-closes an already released libuv poll handle, and StorageNATS now recreates consumer connections that the client library has closed permanently after repeated authorization failures. The current head also adds focused regression coverage for core NATS, stopped/refresh flows, and JetStream backlog/redelivery recovery. I did not find a remaining correctness, safety, or coverage issue in the current diff beyond the points already addressed in the existing review threads.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit d00e52d.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 45/47 (95.74%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix submodule changed At least one submodule changed in this PR. pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Sep 13, 2026
A streaming cycle which was in flight when the broker dropped the connection
still inserts the messages it had, so a fixed wait followed by an equality
assertion could see the count move for a reason which is not the defect under
test. Wait for the count to stop growing instead, which asserts that the
outage is real and returns a usable baseline for the recovery check.

Also connect once per attempt while the credentials are rejected, instead of
the default five times, so the retry loop is easier to read in the log.

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 13, 2026
The callback fires for every closed connection, including the one a table
closes itself on shutdown, so its message read as "the client library gave up"
for a connection which was closed on purpose. A closed consumers connection is
already reported per table by `StorageNATS`, with the table name in the
logger, so the callback added nothing but a misleading warning.

The asynchronous error handler stays: it is the one which reports the rejected
authentication, which the library otherwise prints to `stderr`.
Comment thread src/Storages/NATS/StorageNATS.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 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d00e52d57 with master 0d04f2bc2 (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

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.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.12 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +4.6 s (+12%) in total before that adjustment.

Job report

Replacing a closed consumers connection also resubscribes, so a table under
`SYSTEM STOP` or `SYSTEM PAUSE` would have reattached a live subscription as
soon as the broker accepted its credentials again. A stopped table must hold
no subscription: with core NATS a message delivered to it is dropped, and in a
queue group it is taken away from the members which are still running.

The streaming task keeps running while the table is blocked, so the connection
is rebuilt on the tick after `SYSTEM START`, and the one-shot subscription a
`SYSTEM REFRESH` on a stopped table is entitled to is still opened by the
streaming task itself, as before.

The new test asserts the broker sees no subscription while the table is
stopped, even once its credentials are accepted again, and that the table
resumes on `SYSTEM START`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Thanks - the blocker is real, I reproduced the reasoning in the code: initializeConsumersFunc calls subscribeConsumers without consulting stream_control.isBlocked(), and before this PR a blocked table with attached views never reached that function (threadFunc keeps rescheduling itself and only hands over to the initialization task when there are no views). The new closed-connection path handed over unconditionally, so a stopped table would have reattached a subscription as soon as the broker accepted its credentials again - and in a queue group that takes messages away from the members which are still running.

Fixed in d532c82 by not handing over while the stream is blocked. The streaming task keeps running while the table is stopped, so the connection is rebuilt on the tick after SYSTEM START, and the one-shot subscription a SYSTEM REFRESH on a stopped table is entitled to is still opened by threadFunc itself, exactly as before.

Added test_stopped_nats_table_does_not_resubscribe_after_rotation, which stops the table, drives the credential rejection to the point where the client library closes the connection, accepts the credentials again, and asserts the broker sees no new subscription and the table consumes nothing - then that SYSTEM START brings it back.

…RESH`

The previous commit refused to reinitialize the consumers of a stopped or
paused table whose connection the client library had closed, so that the
table would not subscribe while it is supposed to hold no subscription. That
went too far: the streaming cycle only runs while the connection is up, so a
stopped table whose credentials had been rejected could not run the one
out-of-order cycle a `SYSTEM REFRESH` entitles it to; it stayed inert until
`SYSTEM START`.

The connection and the subscription are different things. A stopped table
keeps its connection and only drops its subscription, so `threadFunc` now
rebuilds a closed connection - and the consumers bound to it - in place,
regardless of whether the table is blocked, and does not touch the
subscription. Whether the new consumers subscribe is decided by the same
`claimCycle` decision as for any other cycle: a running table subscribes and
streams, a blocked table stays unsubscribed, and a blocked table with a
pending refresh permit runs its single cycle and unsubscribes again. Handing
the table over to the initialization task is no longer needed, as that task
subscribes unconditionally.

Added `test_stopped_nats_table_refreshes_after_rotation`: it stops the table,
drives the credential rejection until the client library closes the
connection, accepts the credentials again and checks that the table rebuilds
the connection without subscribing, then that `SYSTEM REFRESH` consumes once
and leaves the table stopped and unsubscribed, and that `SYSTEM START` resumes
consumption. The one-shot cycle ends as soon as the consumer has nothing
buffered, which is right away when it has just subscribed, so the test holds
the block open with `nats_wait_for_flush_interval`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Storages/NATS/StorageNATS.cpp Resolved
The recovery path that replaces a connection the client library closed for
good is shared between core `NATS` and JetStream, but only the core half was
covered: the fake broker speaks no JetStream. For JetStream the transition is
different - `dropConsumers` tears down the durable pull consumer's
subscription with messages possibly still unacknowledged, and the table has
to resume through a fresh subscription to the same durable consumer, with
the broker redelivering what was not acknowledged. That needs a real broker.

`nats_auth_proxy.py` sits between the table and the `nats1` broker (which
runs with JetStream and requires TLS, so the proxy terminates it): it relays
the protocol verbatim except that it answers `INFO` itself and, while its
state file says `reject`, answers every `CONNECT` with
`-ERR 'Authorization Violation'` and drops the live connections - exactly
what a broker does to a client whose password was rotated.

`test_nats_jetstream_credentials_rotation.py` drives a JetStream table through
the rotation: the client library closes the connection, messages published
meanwhile stay in the stream, and once the credentials are accepted again the
table drains that backlog exactly once, keeps consuming, and leaves nothing
pending acknowledgement. A second test leaves ten delivered messages
unacknowledged (through a view whose insert fails) when the connection is
closed and checks that the durable consumer redelivers all of them to the
rebuilt consumer.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Storages/NATS/NATSConnection.cpp Resolved
…rver log

The asynchronous error handler of the client library reports the rejected
authentication, but it knows only the `NATSConnection`, and the only mapping
from that pointer back to a table was a `LOG_DEBUG` line. With several `NATS`
tables on one server an `Authorization Violation` was not actionable at normal
log levels.

The library keeps the last error on a connection it closed for good, so
`StorageNATS` now reports it, under its own logger which carries the table
name, when it replaces the closed connection:

    StorageNATS (test.nats): The NATS client library closed the connection to
    cluster: [hidden] for good. Last error: Authorization Violation. Creating
    a new one

Both rotation tests now wait for that line, with the table name and the error.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

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

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 14, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 14, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #119853 to 26.8: Fix a server crash on a `NATS` table whose credentials the broker rejects
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #119853 to 26.6: Fix a server crash on a `NATS` table whose credentials the broker rejects
clickhouse-gh Bot added a commit that referenced this pull request Sep 15, 2026
Backport #119853 to 26.7: Fix a server crash on a `NATS` table whose credentials the broker rejects
PedroTadim added a commit that referenced this pull request Sep 15, 2026
Backport #119853 to 26.3: Fix a server crash on a `NATS` table whose credentials the broker rejects
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Sep 15, 2026
…ble whose credentials the broker rejects
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…ble whose credentials the broker rejects
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…ble whose credentials the broker rejects
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…ble whose credentials the broker rejects
alexey-milovidov pushed a commit to germiBest/ClickHouse that referenced this pull request Oct 14, 2026
… is replaced

`StorageNATS::consumers_connection` was an unsynchronized `shared_ptr`.
Since ClickHouse#119853, `createConsumersConnection` resets it to null on a
background task when the NATS client library closed the connection for
good (e.g. the broker rejected rotated credentials), then reconnects.
`read` checked the member for null and dereferenced it again after
`getDependentViews`, `getSampleBlockForColumns` and `addSettings`, so a
reset in between made `NATSConnection::isConnected` run on a null
pointer and the server died with SIGSEGV. `threadFunc` and
`streamToViews` had the same check-then-reread, and both background
tasks (`initializeConsumersFunc`, `threadFunc`) could run
`createConsumersConnection` and `createConsumers` concurrently.

The member is now `TSA_GUARDED_BY(consumers_connection_mutex)`, a mutex
held only to copy or assign the pointer, and every reader takes one
copy for its check and its use. A query that copied a connection which
is then replaced keeps the old object alive, sees it closed and fails
with `CANNOT_CONNECT_NATS`.

A second mutex, `consumers_setup_mutex`, serializes
`createConsumersConnection` and `createConsumers`. `createConsumers`
takes one snapshot of the connection under it, throws
`CANNOT_CONNECT_NATS` when there is none (both callers already log and
reschedule), and builds every consumer on that snapshot. One mutex
would deadlock: `dropConsumers` waits, under the setup lock, for the
consumers that `streamToViews` holds while it reads the connection. The
connection mutex is never held across `dropConsumers` or the connect
wait, and the old connection is destroyed after it is released.

The new pause failpoint `nats_pause_before_checking_direct_select_connection`
holds a direct `SELECT` between its check and its use, so the
regression test replaces the connection deterministically.

Closes ClickHouse#120199.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

NATS engine: whole-server crash (segfault in the NATS libuv adapter) when the NATS server rejects the table credentials after a rotation

4 participants