Repository navigation
Fix TSAN data race in executeASTFuzzerQueries clearing caller's transaction - #103158
Algunenano merged 14 commits into
Conversation
…action
`executeASTFuzzerQueries` called `context->setCurrentTransaction(NO_TRANSACTION_PTR)`
and `context->getQueryContext()->getSessionContext()->setCurrentTransaction(NO_TRANSACTION_PTR)`
on the caller's query and session contexts, outside any lock. `Context::setCurrentTransaction`
writes `merge_tree_transaction` with no synchronization, while other threads concurrently
read that same field from the same `Context` under the shared `Context::mutex` via
`Context::createCopy`. The race is exposed under `RESTORE ASYNC` (or any background work
that keeps scheduling `Context::createCopy` on the caller's query context after the
finish callback fires) when `ast_fuzzer_runs > 0` is set — the stress test profile does
this by default, and the finish callback runs on the TCP handler thread while
`Restore_MakeTbl` workers are still doing `Context::createCopy(query_context)`.
TSAN report from master serverfuzz amd_tsan (STID 2604-385d):
Read of size 8 at 0x...9e8 by thread 'Restore_MakeTbl':
shared_ptr<MergeTreeTransaction>::shared_ptr(...) shared_ptr.h:445
ContextData::ContextData(const ContextData &) Context.cpp:1254
Context::Context(const Context &) Context.cpp:1271
Context::createCopy(ContextPtr const &) Context.cpp:1300
RestorerFromBackup::createTable(...) RestorerFromBackup.cpp:773
Previous write of size 8 at 0x...9e8 by thread 'TCPHandler':
shared_ptr<MergeTreeTransaction>::operator=(...) shared_ptr.h:516
Context::setCurrentTransaction(...) Context.cpp:7184
executeASTFuzzerQueries(...) executeQuery.cpp:2113
executeQuery::$_0::operator()(...) executeQuery.cpp:2262
BlockIO::onFinish(...) BlockIO.cpp:70
TCPHandler::runImpl() TCPHandler.cpp:870
Move the reset onto the fuzz session context AFTER `makeSessionContext`, so it mutates
a fresh copy that no other thread can observe. The net behaviour for fuzzed queries is
identical (they still run with no inherited transaction — the fuzz session context is
copied from the caller, then cleared on the copy, then `fuzz_context` is copied from the
already-cleared `fuzz_session_context`), but the caller's `Context` is no longer touched.
This also fixes a latent correctness bug: the previous code silently cleared the user's
active transaction whenever the finish callback fired with `ast_fuzzer_runs > 0`, causing
`COMMIT` to fail with `INVALID_TRANSACTION` after a fuzzed query. The new regression test
`04104_ast_fuzzer_preserves_caller_transaction` locks this in: it reproduces the failure
on the old code (`COMMIT` throws `INVALID_TRANSACTION`) and passes after the fix.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=9ff1683ea9f555f30717c98bf05063c7e94bb4bf&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20amd_tsan%29
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Pre-PR validation gatea) Deterministic repro? b) Root cause explained? c) Fix matches root cause? d) Test intent preserved? e) Both directions demonstrated? f) Fix is general, not a narrow patch? Session: cron:clickhouse-ci-task-worker:20260420-131500 |
|
cc @KochetovNicolai @alexey-milovidov @Algunenano — could you review this TSAN race fix in the server-side AST fuzzer path? It's a narrow 10-line change in |
|
Workflow [PR], commit [1388c1f] Summary: ✅
AI ReviewSummaryThis PR moves the AST fuzzer's transaction cleanup off the caller Final Verdict✅ No new findings. The previously reported issues appear resolved in the current head. |
@groeneai, this reminds me of #92103 which fixed a crash that was happening for a similar reason But isn't it a more fundamental problem with async backup/restore? Maybe async tasks shouldn't share the same context that can be used concurrently by other queries? |
|
@tavplubix, thanks for the cross-link. You're right, this is the same architectural problem. The three known instances share one root:
I agree with the architectural direction PR #92103's own TODO calls out: "Get rid of using PR #103158 is still useful as a targeted fix for the Do you prefer:
Either way I'm happy to drive it. The Cloud |
|
@groeneai try addressing the root cause because, as you mentioned, similar issues seem to be possible in other places |
Moving the transaction reset onto the fuzz session-context copy fixed the write-vs-createCopy race on the caller context, but the fuzz copy itself can still escape. With ast_fuzzer_any_query=true a fuzzed async RESTORE/BACKUP goes through BackupsWorker::startRestoring, which stores the passed context as query_context and schedules background workers that read it via Context::createCopy under the shared Context::mutex. The per-iteration cleanup in executeASTFuzzerQueries then mutates that escaped context without the mutex, reintroducing the same merge_tree_transaction data race on the fuzz copy. Skip BACKUP/RESTORE queries entirely in the fuzzer. The fuzzer is the only code path that mutates a context after it has been handed to async backup/restore work, and fuzzing backup/restore has negligible value (no real backup target). Demonstrated locally: with the skip removed, a fuzzed async BACKUP/RESTORE is re-executed by the fuzzer and escapes to BackupsWorker background workers; with the skip, no BACKUP/RESTORE query is fuzzed. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@tavplubix following up on your root-cause directive. I pushed a broader fix (commit bfc7a72) addressing the concern that the same race was still possible elsewhere. The realistic root cause of this specific race is the AST fuzzer itself. After auditing the paths: the fuzzer is the only code that mutates a So rather than re-copying/stripping at every backup/restore startup boundary (which touches the backup/restore hot path and is easy to get subtly wrong), I skip The pre-existing PR #92103 pattern ( Validation in both directions on an ASan build:
|
|
Heads up on a CI-contract issue, not a real failure: The Bugfix-validation job downloads the master HEAD release binary and requires the new regression test to FAIL on it. A TSAN-only data race does not fail deterministically in a release build, and The entire change lives in @tavplubix could you drop the Session: cron:clickhouse-ci-task-worker:20260604-013100 |
…zzer-transaction-2604-385d
After merging master, the comment before `implicit_tcl_executor->commit(context)` claimed the AST fuzzer "resets the transaction stored in the session and query contexts". That is exactly the behavior this PR removes: the fuzzer now resets the transaction only on the fuzz session-context copy, never on the caller's `context`. Drop the obsolete paragraph; the `commit(context)` call remains justified by the preceding issue ClickHouse#80428 note. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…zzer-transaction-2604-385d # Conflicts: # src/Interpreters/executeQuery.cpp
CI finish ledger — 44f7661Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
None PR-caused: this PR's diff is Session id: cron:our-pr-ci-monitor:20260629-043000 |
…context Background `RESTORE` workers (`createDatabase`/`createTable`, running on the `RESTORE` thread pool) copied the live query context via `Context::createCopy(query_context)`. For a `RESTORE ASYNC` query the originating thread can still touch that same `Context` after the query has returned (for example the server-side AST fuzzer resets `merge_tree_transaction` in its finish callback), so the background copy reads `merge_tree_transaction` under `Context::mutex` while that thread writes it -- the TSAN data race seen on `BuzzHouse (amd_tsan)` (STID 3336-2c6d). `RestoreStarter` already creates a dedicated `restore_context` copy that the restorer holds as `context`, precisely so background work does not depend on the live query context. Switch the remaining `query_context` uses in `RestorerFromBackup` (`createDatabase`, `createTable`, `checkTable`, `checkAccessForObjectsFoundInBackup`) over to `context`, and drop the now-unused `query_context` member and constructor/`doRestore` parameter. This resolves the long-standing `TODO: Get rid of using query_context in class RestorerFromBackup` and the root cause raised in review on ClickHouse#103158 (background backup/restore tasks must not share a `Context` that another query can mutate concurrently). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Pre-PR validation gate (test-strengthening for 04339, HEAD 40ebd9c) (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260701-234200 |
…d DDL output
The Style check requires system.query_log queries to carry a
current_database = currentDatabase() condition; the client (initial) row of
the fuzzed ALTER carries the counter and runs in the current database, so the
existing initial_query_id scope plus this condition still yield a positive
delta.
In the default distributed_ddl_output_mode = throw, the replicated CREATE
TABLE / ALTER / DROP TABLE printed per-replica status rows ("s1 r1 OK 0 0")
to stdout, which are not part of the checked output and made the flaky check
fail on the reference diff. Pin distributed_ddl_output_mode = none on every
DDL invocation so stdout stays clean regardless of the CI profile.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (04339 Style + flaky-check fix, HEAD 02ccd89) (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260702-012800 |
The previous commit detached metadata_transaction from the fuzz context to stop a fuzzed replicated DDL from adding ops to an already-executed ZooKeeperMetadataTransaction (STID-3729, "Cannot add ZooKeeper operation because query is executed"). That only moved the abort: with the transaction detached, is_replicated_database_internal still makes shouldReplicateQuery() route a fuzzed ALTER to a local commit, so it reaches DatabaseReplicated::commitAlterTable with no transaction while the DDL worker is active and trips chassert(!ddl_worker || !ddl_worker->isCurrentlyActive() || txn) at DatabaseReplicated.cpp:2435 (STID-3817). The same invariant guards commitCreateTable, dropTable, renameTable and detachTablePermanently. Fix the root cause instead: do not fuzz at all when an internal replicated-DDL execution is in flight on the context. DatabaseReplicatedDDLWorker re-executes a committed DDL entry whose serialized settings still carry ast_fuzzer_runs, so the fuzzer fires again on the entry's live, single-shot metadata transaction. The initiating client query is still fuzzed normally, so this only drops the redundant re-fuzz during log replay, and it covers both the addOp (3729) and the commit-null-txn (3817) sites at once while leaving the commit* assertions intact as real invariants. This replaces the metadata_transaction detach and its Context::resetZooKeeperMetadataTransaction helper. The regression test 04339 now asserts the fuzzer skipped the internal DDL re-execution (ASTFuzzerSkippedReplicatedDDLInternal > 0) instead of the detach. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed 776eaf0 — replaces the The detach fixed STID-3729 ( Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260702-010300 |
CI finish ledger — 776eaf0Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20260702-073000 |
|
@groeneai, as all fixes have been merged, please update the branch. |
…zzer-transaction-2604-385d
|
@alexey-milovidov Branch updated: merged current master ( |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 30/30 (100.00%) · Uncovered code |
CI finish ledger — 1388c1fEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
No PR-caused failure. All checks pass on head 1388c1f (the earlier flaky/upgrade-check lines from prior heads did not recur on this SHA). Session id: cron:our-pr-ci-monitor:20260707-033000 |
Algunenano
left a comment
There was a problem hiding this comment.
I don't like the solution, but I couldn't find anything better
|
@alexey-milovidov could you apply Two TSAN hits, both 26.6, both after this merged:
The reported frames are The label expands to 26.7 and 26.6. 26.7 already contains The port conflicts, so it will come out as a 26.5 and 26.3 carry the same pre-fix lines but have not reproduced the signature in 90 days; |
Cherry pick #103158 to 26.6: Fix TSAN data race in executeASTFuzzerQueries clearing caller's transaction
…es clearing caller's transaction
Backport #103158 to 26.6: Fix TSAN data race in executeASTFuzzerQueries clearing caller's transaction
…context Background `RESTORE` workers (`createDatabase`/`createTable`, running on the `RESTORE` thread pool) copied the live query context via `Context::createCopy(query_context)`. For a `RESTORE ASYNC` query the originating thread can still touch that same `Context` after the query has returned (for example the server-side AST fuzzer resets `merge_tree_transaction` in its finish callback), so the background copy reads `merge_tree_transaction` under `Context::mutex` while that thread writes it -- the TSAN data race seen on `BuzzHouse (amd_tsan)` (STID 3336-2c6d). `RestoreStarter` already creates a dedicated `restore_context` copy that the restorer holds as `context`, precisely so background work does not depend on the live query context. Switch the remaining `query_context` uses in `RestorerFromBackup` (`createDatabase`, `createTable`, `checkTable`, `checkAccessForObjectsFoundInBackup`) over to `context`, and drop the now-unused `query_context` member and constructor/`doRestore` parameter. This resolves the long-standing `TODO: Get rid of using query_context in class RestorerFromBackup` and the root cause raised in review on ClickHouse#103158 (background backup/restore tasks must not share a `Context` that another query can mutate concurrently). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…uzzer-transaction-2604-385d Fix TSAN data race in executeASTFuzzerQueries clearing caller's transaction
The server-side AST fuzzer (
executeASTFuzzerQueries, active only whenast_fuzzer_runs > 0) used to clear the transaction on the caller's query and sessionContextwith no lock held:Context::setCurrentTransactionwritesmerge_tree_transactionunsynchronized, while other threads read the same field under the sharedContext::mutexviaContext::createCopy. UnderRESTORE ASYNCwithast_fuzzer_runs > 0,RestorerFromBackupbackground workers keep copying the context while the fuzzer finish callback overwrites the transaction pointer, producing the TSAN race (STID 2604-385d read side, 3336-2c6d write side, seen onStress test/BuzzHouse (experimental, serverfuzz, *_tsan)).Fix
BACKUP/RESTOREqueries. An async backup/restore returns fromexecuteQueryimmediately whileBackupsWorkerkeeps the (fuzz) context alive for background workers that read it viaContext::createCopy; mutating that escaped copy afterwards reintroduces the same race. The fuzzer has negligible value on backup/restore (no real backup target), so skipping them is safe.Tests:
04104_ast_fuzzer_preserves_caller_transaction(caller transaction preserved acrossast_fuzzer_runs > 0) and04305_ast_fuzzer_skips_backup_restore(server stays alive and data intact with fuzzed backup/restore).The whole change lives in fuzzer-only code gated on the
ast_fuzzer_runsCI/stress-test setting, never a production user path, so this is categorized as a CI fix.Changelog category (leave one):
Documentation entry for user-facing changes
Version info
26.6.4.16