Skip to content

Copy a table function's AST per read of a Distributed table - #115107

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-distributed-table-function-ast-race
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-distributed-table-function-ast-race

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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 data race when a Remote/RemoteSecure table (or a Distributed table 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

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::parseArguments assigns args[0] = database_ast after folding the database name to a literal. Two concurrent queries against the same table therefore write and read the same ASTPtr with no synchronization. The raced eight bytes are the intrusive_ptr pointer slot, whose swap and operator-> are not atomic, so the consequence is a use-after-free rather than a torn value.

AST fuzzer (amd_tsan) reported it as ThreadSanitizer: data race (STID: 3616-438e) between StorageMerge::evaluateDatabaseName (read, intrusive_ptr::operator->) and TableFunctionMerge::parseArguments (write, intrusive_ptr::swap), both under SelectStreamFactory::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::read takes one copy of the member per call and passes it to all three consumers, and distributedWriteBetweenDistributedTables does the same for the source storage's member. That covers every table function reachable through these paths, so no individual parseArguments changes. Parsing still rewrites its arguments in place, because that normalization is what a CREATE persists: merge(currentDatabase(), '^t') is still stored as merge('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 SELECT whose optimized route is asserted, not assumed.

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

Copy link
Copy Markdown
Collaborator Author
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
two test gaps; round 2 found nothing and is what is published here.

Round 1, both fixed:

  • ❌ The write-path copy had no oracle. The regression test issued only SELECTs, and the
    mutation arm reverted only the read copy, so reverting the copy in
    distributedWriteBetweenDistributedTables left the suite green: half the diff was
    unwitnessed. Fixed by adding a concurrent parallel INSERT SELECT phase and a fourth build
    that reverts only that copy. It now reports a race in 3 of 3 rounds, every report naming
    distributedWriteBetweenDistributedTables and none naming the read path, so each half is
    proven separately rather than jointly. The optimized route is asserted positively against
    two negative controls, because that path falls back silently and would otherwise pass
    vacuously.
  • ❌ 64 simultaneous clients would not survive the sanitizer lanes. clickhouse-test caps
    a test's process group at 10 GiB on sanitizer builds, and a single instrumented client
    measured 424 MiB peak RSS, so 64 of them is roughly 26 GiB. Concurrency was kept, not
    lowered: one clickhouse-benchmark -c 32 per definition holds a measured 32 concurrent
    server-side queries in 2 client processes at 406 MiB, and both mutation arms still witness
    the race in that form.
  • ⚠️ Test metadata: # Tags: shard, and DROP ... IF EXISTS at both ends.

Round 2 verdicts. Gate: 0 findings. Of my own notes, one was actionable and the rest were
confirmations:

  • ⚠️ The PR description still described readers only, which would have implied the write-path
    copy was untested. Rewritten here before publishing; no code change.
  • 💡 The reverted-copy evidence was re-symbolized independently rather than taken from the
    write-up, since that run used symbolize=0 and its raw log holds only hex offsets. Frames
    confirm two independent TCPHandler threads on the same eight bytes through the write path.
  • 💡 count() = 1700 was checked for determinism: clickhouse-benchmark counts a failed query
    toward its iteration total rather than retrying, and async insert cannot apply to an
    INSERT SELECT, so a lost insert makes the test fail rather than pass quietly.
  • 💡 Leaving getStructureOfRemoteTable mutating is deliberate: it folds and then formats the
    AST into the DESC TABLE sent to shards, so copying there would ship an unfolded
    currentDatabase().

Validation: 50 randomized runs through clickhouse-test, 50 passed, no sanitizer reports;
6 copies in parallel, 6 of 6.

@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [30e3797]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) FAIL
04921_remote_table_function_concurrent_read FAIL cidb
04921_remote_table_function_concurrent_read FAIL cidb
04921_remote_table_function_concurrent_read FAIL cidb
04921_remote_table_function_concurrent_read FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
04921_remote_table_function_concurrent_read FAIL cidb
LLVM Coverage FAIL
Generate LLVM Coverage Diff Report FAIL cidb

AI Review

Summary

This PR fixes the shared-AST race in StorageDistributed by cloning the stored table-function AST once per operation before parseArguments can rewrite it in place, and adds a stateless regression test that exercises concurrent reads plus the optimized INSERT SELECT path. I reviewed the current diff together with the existing PR discussion and did not find a remaining correctness, compatibility, or test-coverage issue that warrants a new inline review comment.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 16 x 25 concurrent SELECT count() against one Remote('127.0.0.1', merge(currentDatabase(), '^t$')) table under TSAN reports on the first attempt; reproduced independently on a second binary. A single wave of 32 readers also suffices, which is the form the committed test uses.
b Root cause explained? Yes. StorageDistributed::remote_table_function_ptr (StorageDistributed.h:239) lives as long as the storage and is passed unguarded to TableFunctionFactory::get on every read; parseArguments rewrites the argument slots in place (TableFunctionMerge.cpp:111/121/124). The raced 8 bytes are intrusive_ptr::px, whose swap/operator-> are non-atomic, so the consequence class is use-after-free. The two racing threads are two concurrent queries, not two shards: the shard loop is sequential and already clones the query AST per shard.
c Fix matches root cause? Yes. The defect is concurrent reuse of one AST, so each operation gets its own copy at the owner (StorageDistributed::read, distributedWriteBetweenDistributedTables). No lock, no guard at the crash site, no suppression.
d Test intent preserved / new tests added? Yes. No existing test changed or weakened. New 04921_remote_table_function_concurrent_read.sh, parallel-safe with no no-parallel tag, covering both merge arities, both the read path and the parallel INSERT SELECT path, and asserting the persisted definition still holds the folded literal. The INSERT SELECT phase asserts that the optimized route was actually taken, because that route falls back silently; the assertion was checked against two configurations where it must report 0.
e Both directions demonstrated? Yes, for each half of the change separately, with four separately built binaries, each confirmed by Build-ID on disk and via SELECT lower(buildId()): pristine base reports 6 races; with both copies, 0 races and every query correct; reverting only the read-path copy brings the read-path races back; reverting only the write-path copy reports races through distributedWriteBetweenDistributedTables in 3 of 3 rounds and through no other frame.
f Fix is general across code paths? Yes. Fixing at the owner covers every mutating parseArguments reachable through Remote() at once (~13 implementations, e.g. TableFunctionFormat.cpp), so none needs its own change. A re-grep of all 32 remote_table_function_ptr occurrences confirms no other read-time consumer; the symmetric write-side path is fixed too. getStructureOfRemoteTableInShard is reached only during construction, where the in-place normalization is the documented, required behaviour.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Both merge arities are tested (2-argument, the reported write, and 1-argument). A table with no table-function target short-circuits on the null check and copies nothing. The fix copies the whole AST, so it is independent of argument shape, arity and type.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no serialization format change, so no SettingsChangesHistory.cpp entry. Persisted definitions are unchanged: merge(currentDatabase(), '^t') still reads back as merge('db', '^t') in SHOW CREATE TABLE, verified on the fixed binary.
i Invariants and contracts preserved? Yes. Construction-time normalization, which parseRemoteFunctionArguments.cpp:50-56 documents callers as relying on, is untouched; only read-time sharing changes. The copy is taken before parseArguments' throw sites, so an invalid query wastes one refcounted copy and leaks nothing, and read()'s early returns happen after it. No lock is introduced, so there is no new ordering to audit.

Session id: cron:clickhouse-impl-slot-6:20260817-035900

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 17, 2026
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.
@novikd novikd self-assigned this Aug 17, 2026
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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 30e3797ef with master cb425829a (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
Binary Master PR Δ
programs/clickhouse-stripped 700.93 MiB 697.91 MiB -3.01 MiB (-0.43%)

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 units

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

Job report


/// `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;

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.

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.

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.

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 is T * px (intrusive_ptr.hpp:179), a plain non-atomic pointer. The read is operator-> at :162 (return px); the previous write is swap at :174 (px = rhs.px, reached via operator= at :116).
  • The raced slot is args[0]: read at TableFunctionMerge.cpp:116 (evaluateDatabaseName(args[0], ...), reaching StorageMerge.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 sets ref_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.

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

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.

@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

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.

This branch has not been deployed

No deployments
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-distributed Distributed table engine & query routing across shards (sharding/load balancing). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants