Repository navigation
Fix a crash of a direct SELECT from a NATS table while its connection is replaced - #125494
Conversation
… 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]>
Internal second-model review (click to expand)
Re-review of the fix commit: no further findings. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20261012-182500 |
|
Workflow [PR], commit [e7fa5c2] Summary: ✅
AI ReviewSummaryThis PR fixes the Final Verdict
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units12 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. |
| 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 |
There was a problem hiding this comment.
@groeneai maybe you can try to release the lock a little earlier? The LOG_WARNING is expensive
There was a problem hiding this comment.
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.
|
@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]>
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]>
Closes: #120199
Related: #119853
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a server crash (segmentation fault) in a direct
SELECTfrom aNATStable 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-ltshas the same code), a directSELECTfrom aNATStable 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_connectionis a plainshared_ptrwith no synchronization.readchecks 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 runcreateConsumersConnectionandcreateConsumersat the same time.Change:
consumers_connectionis 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 withCANNOT_CONNECT_NATS.createConsumersConnectionandcreateConsumers.createConsumersbuilds the consumers on one non-null connection snapshot and throwsCANNOT_CONNECT_NATS(the callers retry) when there is none. It has to be a separate mutex, becausedropConsumerswaits under it for consumers thatstreamToViewsholds while it reads the connection.SELECT, per streaming cycle and per consumer creation, none per message.Validation: the new integration test pauses a direct
SELECTbetween 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.pyandtest_system_stop.pypass.Workflow [PR]
Sync PR [sync-upstream/pr/125494]
Version info
26.10.1.2348-master(included in26.10and later)