Repository navigation
Conversation
StorageDistributed keeps remote_table_function_ptr for the lifetime of the
storage and passes it, unguarded, to TableFunctionFactory::get on every read.
Argument parsing rewrites the argument slots in place: TableFunctionMerge
assigns args[0] = database_ast after folding the database name to a literal,
and about a dozen other table functions do the equivalent. Two concurrent
queries against the same table therefore write and read the same ASTPtr with
no synchronization.
ThreadSanitizer reported it from the AST fuzzer as a race between
StorageMerge::evaluateDatabaseName and TableFunctionMerge::parseArguments,
both below SelectStreamFactory::createForShardImpl. The raced eight bytes are
the intrusive_ptr pointer slot, whose swap and operator-> are not atomic
(IAST::ref_counter is atomic, the slot is not), so the reachable consequence
is a use-after-free rather than a torn value. The shard loop in
ClusterProxy::executeQuery is sequential and already clones the query AST per
shard, so the two racing threads are two concurrent queries: the existing
cloning discipline covers the query and misses the table function.
Fix it at the owner rather than in any single table function. read() takes one
copy per call and passes it to all three consumers, and
distributedWriteBetweenDistributedTables does the same for the source
storage's member. Every table function reachable through these paths is
covered at once, so no individual parseArguments changes.
Parsing still normalizes its arguments in place, which is deliberate:
parseRemoteFunctionArguments documents callers as persisting the result, so
merge(currentDatabase(), '^t') must keep being stored as merge('db', '^t').
Construction-time mutation is the feature; read-time mutation was the bug.
getStructureOfRemoteTableInShard also mutates, but every caller reaches it
during construction, where that normalization is required, so it is left
alone.
Validated under ThreadSanitizer with three separately built binaries. Without
the change, 32 concurrent readers reproduce the reported race; with it the same
run is clean and every query returns the correct result; reverting only the
added copy brings the race back. At 8 readers the test did not witness the
race, so the committed test uses 32.
The test only issued SELECTs, so reverting the copy in distributedWriteBetweenDistributedTables left it green: half the change shipped unwitnessed. It now also runs concurrent INSERT ... SELECT with parallel_distributed_insert_select = 2 against a single-shard Remote destination, which reaches the same member through InterpreterInsertQuery::execute. That route rewrites the statement and ships it to the shard; the ordinary route does not and is taken silently whenever the route's conditions fail, so the test asserts the rewritten statement was actually shipped instead of assuming it. Reverting only that copy now reports a race through distributedWriteBetweenDistributedTables and through no other frame, and reverting only the read-path copy still reports only the read-path race, so each copy is witnessed on its own. The readers moved from 64 background clients to one clickhouse-benchmark process per table function definition. The concurrency is unchanged and stays load-bearing at 32 connections, which is what observes the access where 8 did not; only the process count drops. An instrumented client is a few hundred megabytes and clickhouse-test runs the test's process group under a 10 GiB limit on sanitizer builds, which 64 of them would exceed, and the flaky check runs one copy of a test per worker. The query_log read pins enable_parallel_replicas = 0 and filters on event_date: with the setting randomized the read is re-planned onto the parallel_replicas cluster. The two verification counts pin prefer_localhost_replica = 1, matching the concurrent phase above them, because the single-argument merge() form resolves against the current database and a shard that received the query would look in its own. Tables are dropped if they exist at both ends, and the test is tagged shard for the 127.0.0.1 routing.
Internal second-model review (2 rounds, 0 open findings)Two independent review rounds before this PR was opened. Round 1 bounced the change back for Round 1, both fixed:
Round 2 verdicts. Gate: 0 findings. Of my own notes, one was actionable and the rest were
Validation: 50 randomized runs through |
|
Workflow [PR], commit [30e3797] Summary: ❌
AI ReviewSummaryThis PR fixes the shared-AST race in Final Verdict✅ No new findings. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260817-035900 |
|
cc @devcrafter @Avogar, could you review this? A Distributed/Remote table over a table function keeps one argument AST for the lifetime of the storage, while parseArguments rewrites its argument slots in place, so two concurrent queries read and write the same intrusive_ptr slot; the fix copies the AST once per operation at the owner rather than changing each table function. |
The style check requires every test that reads system.query_log to carry a current_database = currentDatabase() filter, and this test lacked it. Applying that filter directly to the row being asserted would have broken the assertion instead of fixing the style failure: the row is a query the shard ran, and an interserver connection does not carry the initiator's database, so the row's current_database is 'default'. Measured on a local server, the direct form returns 0 where the test expects 1. The filter is applied to the initiator instead, and the shard row is selected by initial_query_id. That satisfies the rule and also scopes the assertion per database, which it previously was not. Same approach as 04625_hash_table_sizes_stats_table_expression_modifiers.sh, which documents the same behaviour. Verified: the full various_checks.sh query_log loop reports 0 failures, clickhouse-test --test-runs 10 passes 10/10, and a negative control that breaks the optimized route still fails the assertion loudly.
The concurrent read phase discarded both benchmark processes' output and waited on them without checking either status, and the counts that follow do not depend on it, so a phase in which every query failed left all six output lines unchanged. Measured: pointing the readers at a nonexistent table still reported [ OK ], which means the primary witness for the read side could go dead without anyone noticing. Each benchmark's status is now checked individually, so a failure prints and the test fails. clickhouse-benchmark exits nonzero for a failing query (60), an unreachable server (210) and an empty query list (92), and bare wait returns the status of the last job only. Verified with three arms: unmodified passes 20/20, broken reader queries now fail, and a broken writer benchmark still fails on the row-count assertion. Parallel-safe, 6 simultaneous copies pass.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units7 translation units recompiled, 19 s compile time in total, 7 of them have a recent master baseline. |
|
|
||
| /// `parseArguments` rewrites a table function's arguments in place, so the AST handed to it must | ||
| /// belong to one operation. This member outlives the query and is read by every concurrent one. | ||
| ASTPtr table_function_for_query = remote_table_function_ptr ? remote_table_function_ptr->clone() : nullptr; |
There was a problem hiding this comment.
It won't fix the data race, because the counter is part of IAST. You need to have separate copies per stream to resolve the data race.
There was a problem hiding this comment.
The counter is in IAST (IAST.h:42, mutable std::atomic<UInt32> ref_counter), but it is not what races here:
- The report is a size 8 race.
std::atomic<UInt32>is 4 bytes and atomic, so TSAN would not report on it. - Both reported frames are in
boost::intrusive_ptr, whose only member isT * px(intrusive_ptr.hpp:179), a plain non-atomic pointer. The read isoperator->at:162(return px); the previous write isswapat:174(px = rhs.px, reached viaoperator=at:116). - The raced slot is
args[0]: read atTableFunctionMerge.cpp:116(evaluateDatabaseName(args[0], ...), reachingStorageMerge.cpp:2130) and written at:121(args[0] = database_ast). That is frame for frame the CI report. clone()does not share the counter either: the copy constructor setsref_counter(0)(IAST.cpp:106-112).
On per-stream copies: within one read() the clone is not shared between streams. createForShard runs in a sequential shard loop (ClusterProxy/executeQuery.cpp:415, :454); ReadFromRemote holds the ASTPtr by value (ReadFromRemote.h:61), only null-checks it and never calls TableFunctionFactory; the lazy path captures its own copy. So one copy per operation is what removes the shared slot.
Four distinct binaries under TSAN: pristine 6 races, with the fix 0, read-side clone reverted 6 races back, write-side clone reverted races in 3 of 3 rounds naming only write-path frames.
If you have a specific path in mind where two streams of one query reach parseArguments on the same node, name it and I will fix it there.
|
Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a data race when a
Remote/RemoteSecuretable (or aDistributedtable over a table function) was read by several queries at once. A table function's arguments are rewritten in place while they are parsed, and every query parsed the same AST that the storage keeps for its lifetime, so a concurrent read could observe a partially rewritten argument.Description
StorageDistributedkeepsremote_table_function_ptrfor the lifetime of the storage and passes it, unguarded, toTableFunctionFactory::geton every read. Argument parsing rewrites the argument slots in place:TableFunctionMerge::parseArgumentsassignsargs[0] = database_astafter folding the database name to a literal. Two concurrent queries against the same table therefore write and read the sameASTPtrwith no synchronization. The raced eight bytes are theintrusive_ptrpointer slot, whoseswapandoperator->are not atomic, so the consequence is a use-after-free rather than a torn value.AST fuzzer (amd_tsan)reported it asThreadSanitizer: data race (STID: 3616-438e)betweenStorageMerge::evaluateDatabaseName(read,intrusive_ptr::operator->) andTableFunctionMerge::parseArguments(write,intrusive_ptr::swap), both underSelectStreamFactory::createForShardImpl: CI report. That commit touches none of the racing files and the mutation predates it, so it only exposed a latent race. The shard loop is sequential and already clones the query AST per shard, so the racing threads are two concurrent queries, not two shards.I fixed it at the owner:
StorageDistributed::readtakes one copy of the member per call and passes it to all three consumers, anddistributedWriteBetweenDistributedTablesdoes the same for the source storage's member. That covers every table function reachable through these paths, so no individualparseArgumentschanges. Parsing still rewrites its arguments in place, because that normalization is what aCREATEpersists:merge(currentDatabase(), '^t')is still stored asmerge('db', '^t').Reachable from ordinary SQL: create
ENGINE = Remote('127.0.0.1', merge(currentDatabase(), '^t'))and read it concurrently.Validated under ThreadSanitizer with four separately built binaries: 32 concurrent readers reproduce the race without the change and the run is clean with it, and each copy is witnessed on its own by reverting just that one. The new test covers concurrent reads and a concurrent parallel
INSERT SELECTwhose optimized route is asserted, not assumed.