Skip to content

Fix a crash of a direct SELECT from a NATS table while its connection is replaced - #125494

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-nats-direct-select-connection-race
Oct 14, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-nats-direct-select-connection-race

Conversation

@groeneai

@groeneai groeneai commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120199
Related: #119853

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

Fixed a server crash (segmentation fault) in a direct SELECT from a NATS table while the table replaces a connection that the NATS client library closed for good, for example after the broker rejected rotated credentials. Closes #120199.

Description

On 26.8 and 26.3 LTS (the recovery from #119853 was backported; v26.8.18.2-lts has the same code), a direct SELECT from a NATS table with no materialized view can crash the server with a segmentation fault (NATSConnection::isConnected <- StorageNATS::read). It happens when the table replaces its connection while the query is being planned, which it does after the NATS client library closed the connection for good, e.g. because the broker rejected rotated credentials.

StorageNATS::consumers_connection is a plain shared_ptr with no synchronization. read checks it for null and dereferences it again a few calls later, while a background task resets it to null and reconnects. The two background tasks can also run createConsumersConnection and createConsumers at the same time.

Change:

  • consumers_connection is guarded (TSA_GUARDED_BY) by a mutex that is held only to copy or assign the pointer. Every reader takes one copy and uses it for both the check and the use, so a query that copied the old connection sees it closed and fails with CANNOT_CONNECT_NATS.
  • A second mutex serializes createConsumersConnection and createConsumers. createConsumers builds the consumers on one non-null connection snapshot and throws CANNOT_CONNECT_NATS (the callers retry) when there is none. It has to be a separate mutex, because dropConsumers waits under it for consumers that streamToViews holds while it reads the connection.
  • Cost: one uncontended lock per direct SELECT, per streaming cycle and per consumer creation, none per message.

Validation: the new integration test pauses a direct SELECT between the check and the use (new failpoint) while the table replaces the connection. It crashes master built with only the failpoint, and passes 50/50 with the fix. The reproducer from the issue crashed an unmodified master build 2 of 2 times and passed 2 of 2 times with the fix. test_nats_credentials_rotation.py and test_system_stop.py pass.


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

Version info

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

groeneai and others added 2 commits October 12, 2026 19:12
… 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]>
`dropConsumers` and `createConsumer` are now `TSA_REQUIRES(consumers_setup_mutex)`, so
calling either without the setup lock fails `-Wthread-safety-analysis`. Before, removing
the lock from `createConsumersConnection` or `createConsumers` compiled and passed every
test while bringing back the race between the two background tasks that rebuild the
connection and the consumers. The annotations do not change the generated code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
Finding Verdict
⚠️ The regression test does not catch removing either mutex Agreed for the setup mutex: dropConsumers and createConsumer now require consumers_setup_mutex (TSA_REQUIRES), so deleting either setup lock fails to compile. The connection mutex was already compiler-checked (TSA_GUARDED_BY; deleting the lock in read fails with -Wthread-safety-analysis).
💡 Use Critical Bug Fix for the segfault Kept Bug Fix: the crash is in released 26.8 and 26.3 LTS builds, and I leave the critical category to maintainers.
💡 Shutdown can wait through two serial connect attempts if both background tasks are recovering at once Noted, not changed: it needs both tasks recovering, a shutdown and a failing connect at the same time, and costs one extra connect cycle at most.

Re-review of the fix commit: no further findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test pauses a direct SELECT between its connection check and its use (failpoint nats_pause_before_checking_direct_select_connection) while the table replaces the connection. Master with only the failpoint added: server SIGSEGV 3/3.
b Root cause explained? consumers_connection is an unsynchronized shared_ptr. Since #119853, createConsumersConnection resets it to null on a background task when the client library closed the connection for good, while read checks it for null and dereferences it again later, so NATSConnection::isConnected runs on a null pointer.
c Fix matches root cause? Yes. The member is TSA_GUARDED_BY a mutex held only for a copy or assignment. Every reader uses one copy for both the check and the use, and a second mutex serializes the two writers.
d Test intent preserved / new tests added? New integration test test_direct_select_while_connection_is_replaced in test_nats_credentials_rotation.py. Existing tests unchanged.
e Both directions demonstrated? Same test: master + failpoint SIGSEGV 3/3, fix PASS (50/50). The reproducer from the issue: unmodified master SIGSEGV 2/2, fix PASS 2/2 with 60 connection replacements each.
f Fix is general across code paths? All accesses changed: createConsumersConnection, createConsumers / createConsumer, read, shutdown, threadFunc (2), streamToViews. An unguarded read fails to compile (-Wthread-safety-analysis, checked), and the setup lock is checked the same way (TSA_REQUIRES). RabbitMQ and Kafka never reset a shared connection.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A, concurrency defect. Core NATS and JetStream consumers share the changed path.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change, only an error instead of a crash. The failpoint is test-only.
i Invariants and contracts preserved? The connection mutex is never held across dropConsumers or the connect wait, and no connection is destroyed under it. Lock order is setup -> connection, and readers never take the setup lock. Consumers are still dropped before their connection.

Session id: cron:clickhouse-impl-slot-41:20261012-182500

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e7fa5c2]

Summary: ✅


AI Review

Summary

This PR fixes the StorageNATS direct-SELECT crash by guarding consumers_connection with a mutex, taking stable connection snapshots before use, and serializing connection replacement with consumer creation so the two background tasks cannot rebuild state concurrently. I reviewed the current diff, the surrounding StorageNATS and NATSSource code paths, the new integration test, the prior discussion, the existing inline thread, and the current CI state; I do not see a remaining correctness, concurrency, or evidence gap in the current revision.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). labels Oct 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e7fa5c2e7 with master b4ac7be09 (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

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

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

Job report

if (consumers_connection && consumers_connection->isClosed())
if (connection && connection->isClosed())
{
/// The table name is in the logger. The error handler of the client library reports the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai maybe you can try to release the lock a little earlier? The LOG_WARNING is expensive

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.

Done in e7fa5c2. The closed connection and its consumers are dropped under consumers_setup_mutex, the warning is written with no lock held, and the lock is taken again only for the reconnect, which first re-checks whether the other background task has already reconnected. Every write of consumers_connection now goes through setConsumersConnection, which is TSA_REQUIRES(consumers_setup_mutex), so the build fails if either critical section loses its lock.

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov you have to review this one?

`createConsumersConnection` held `consumers_setup_mutex` while it wrote the
warning about a connection the client library closed for good. Drop the
closed connection and its consumers in a short critical section, log with no
lock held, then take the lock again for the reconnect. The reconnect re-checks
the connection first, so a background task that reconnected in between is
not duplicated; `createConsumers` already throws on a missing connection and
its callers reschedule.

Every write of `consumers_connection` now goes through
`setConsumersConnection`, which requires the setup lock, so the compiler
rejects either critical section without it.

Requested in review: ClickHouse#125494 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Oct 14, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 14, 2026
Merged via the queue into ClickHouse:master with commit 2d616eb Oct 14, 2026
176 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
BorisTyshkevich pushed a commit to BorisTyshkevich/ClickHouse that referenced this pull request Nov 15, 2026
The test raced `DROP TABLE ... SYNC` against a direct `SELECT` by wall
clock: the `SELECT` kept its plan open for ~3 s in a scalar subquery and
pytest sent the `DROP` 1.2 s later, so the `DROP` had to reach the server
within ~1.8 s. In `Integration tests (amd_msan, targeted)` on ClickHouse#112928 the
`DROP`'s client needed 2.23 s to connect, the `SELECT` read the live
metadata first and returned 0 without an error, and the assertion
`'TABLE_IS_DROPPED' in ''` failed.

Add a one-shot pause failpoint `object_storage_queue_pause_in_direct_select`
in `StorageObjectStorageQueue::read()`, after the table is opened and
before the read path takes the metadata handle. It parks the query thread
during planning, never a pipeline worker inside `IProcessor::work()`.
The test now enables it, starts the `SELECT`, waits for the pause, runs
`DROP TABLE` (not `SYNC`: that waits for the paused `SELECT` to release
the table), disables the failpoint and asserts `TABLE_IS_DROPPED`. One
deterministic pass replaces the 10 sleep-based iterations. Same pattern as
`nats_pause_before_checking_direct_select_connection` (ClickHouse#125494).

Related: ClickHouse#112928
Related: ClickHouse#113695

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

can be tested Allows running workflows for external contributors comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). 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 direct SELECT segfaults: read re-reads consumers_connection after reset

4 participants