Repository navigation
Fix a server crash on a NATS table whose credentials the broker rejects - #119853
Conversation
…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
|
Workflow [PR], commit [d00e52d] Summary: ✅
AI ReviewSummaryThis PR fixes the Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit d00e52d.
Changed lines: Changed C/C++ lines covered: 45/47 (95.74%) · Uncovered code |
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.
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`.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units17 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. |
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`.
|
Thanks - the blocker is real, I reproduced the reasoning in the code: 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 Added |
…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]>
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]>
…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]>
Backport #119853 to 26.8: Fix a server crash on a `NATS` table whose credentials the broker rejects
Backport #119853 to 26.6: Fix a server crash on a `NATS` table whose credentials the broker rejects
Backport #119853 to 26.7: Fix a server crash on a `NATS` table whose credentials the broker rejects
Backport #119853 to 26.3: Fix a server crash on a `NATS` table whose credentials the broker rejects
|
@alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
…ble whose credentials the broker rejects
…ble whose credentials the broker rejects
…ble whose credentials the broker rejects
…ble whose credentials the broker rejects
… 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]>
Closes: #118449
A table with
ENGINE = NATStook the whole server down with a segmentation fault when the brokerstarted rejecting its credentials - after a password rotation, or on an expired token, which
reports
Authentication Expiredand takes the same path asAuthorization 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"). Closingit crashed the shared event loop thread which serves every
NATStable of the server:_evStopPollingruns once per reconnect attempt and once more from_closewhen the library givesup, because
_closeonly checksnc->el.attached, which_evStopPollingdoes not clear. Each runasks the
libuvadapter to remove the write and then the read event, and the removal which bringsnle->eventsto zero closes the poll handle and setsnle->handletoNULL. Every furtherremoval then reached the unguarded
uv_close((uv_handle_t*) nle->handle, ...)inuvPollUpdate,and
uv_closefaulted reading the handle's type field at offset0x10.The submodule bump guards
uvPollUpdateagainst a handle which is already gone, and stops asking aconnection which is not being polled to stop polling -
_evStopPollinghands the socket close tothe 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.StorageNATSnow 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 Violationon a connection it closed for good - so that an operator withseveral
NATStables can tell whose credentials to fix: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
stderrby 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
masterand checks both halves of the fix: the server survives, and the table resumes consumingonce 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
nats1broker, which rejects the credentials of the live table on demand, andchecks 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):
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 = NATSwhose 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
26.8.5.10,26.7.9.12,26.6.7.15,26.3.33.85