Skip to content

Cherry pick #103158 to 26.6: Fix TSAN data race in executeASTFuzzerQueries clearing caller's transaction - #114906

Merged
robot-ch-test-poll merged 16 commits into
backport/26.6/103158from
cherrypick/26.6/103158
Aug 24, 2026
Merged

robot-ch-test-poll merged 16 commits into
backport/26.6/103158from
cherrypick/26.6/103158

Conversation

@robot-clickhouse-ci-2

Copy link
Copy Markdown
Contributor

Original pull-request #103158

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 15 commits April 20, 2026 13:46
…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]>
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]>
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 #80428 note.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…zzer-transaction-2604-385d

# Conflicts:
#	src/Interpreters/executeQuery.cpp
… counter

The regression test only checked that the server stayed alive and the restored
rows were intact after fuzzed BACKUP/RESTORE. That is a liveness check: removing
the ASTBackupQuery skip guard in executeASTFuzzerQueries could leave the test
green as long as the extra fuzzed BACKUP/RESTORE happened not to trip the race,
the same reason the release-binary Bugfix validation job could not catch it.

Assert the skip directly. ProfileEvents::ASTFuzzerQueries is incremented only
after the ASTBackupQuery early-continue, so the counter delta across the fuzzed
BACKUP/RESTORE statements must be zero. A positive control (a plain fuzzable
SELECT with ast_fuzzer_runs > 0) must show a non-zero delta, proving the counter
is live so the zero delta is a real skip and not a dead counter. Verified both
directions on a debug build: with the guard the BACKUP/RESTORE delta is 0 (pass);
with the guard removed it becomes non-zero (fail).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The ASTFuzzerQueries delta==0 check was necessary but not sufficient: the
depth (checkDepth), formatting, and >10000-char length guards in
executeASTFuzzerQueries also skip a fuzzed query with a zero counter delta,
so the test could stay green even if the ASTBackupQuery guard were removed.

Move the ASTBackupQuery skip above those other early-continue paths and count
it with a dedicated ProfileEvents::ASTFuzzerSkippedBackupRestore event. The
guard is a top-node dynamic_cast (no recursion), so running it before
checkDepth is safe. The test now asserts the skip counter advances (>0) for
the fuzzed BACKUP/RESTORE while the executed-query counter does not, which is
specific to the query type and cannot be produced by the depth/format/length
skips. A plain fuzzable query is the positive control: executed counter
advances, skip counter does not.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
executeASTFuzzerQueries strips the MergeTree transaction from the fuzz
context copies but left metadata_transaction (the ZooKeeperMetadataTransaction)
in place. When the fuzzer runs inside a replicated-DDL execution (DDLWorker
re-executes a DDL entry whose serialized settings still contain ast_fuzzer_runs,
with ast_fuzzer_any_query = 1), the fuzz context inherits the entry's live
metadata transaction. The fuzzed follow-up DDL then calls
ZooKeeperMetadataTransaction::addOp on an already-executed transaction and
throws 'Cannot add ZooKeeper operation because query is executed', a
LOGICAL_ERROR that aborts debug and sanitizer builds.

Detach metadata_transaction from the fuzz session context alongside the
existing merge_tree_transaction reset (a new Context::resetZooKeeperMetadataTransaction
helper). The reset runs on the copy, so the caller's transaction is untouched.
A new ASTFuzzerClearedMetadataTransaction profile event counts the detach.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
04339 previously only checked that the server stays alive after the fuzzed
replicated DDL. That is not build-mode independent: on a release binary the
leaked-transaction LOGICAL_ERROR ("Cannot add ZooKeeper operation because query
is executed") is thrown by the fuzzed follow-up DDL and caught inside
executeASTFuzzerQueries (Exception aborts the process only in debug/sanitizer
builds), so the outer ALTER still succeeds and 'alive' still prints even if
resetZooKeeperMetadataTransaction() were reverted. The test would stay green.

Assert the contract directly instead: run the fuzzed ALTER with a unique
query_id and check that ProfileEvents['ASTFuzzerClearedMetadataTransaction'] is
non-zero for it. That counter is incremented only when the fuzzer's
resetZooKeeperMetadataTransaction() detaches a live transaction from the fuzz
context, so it is a positive signal that the strip fired. It is attributed to
this ALTER via initial_query_id (both the client statement and the DDLWorker
re-execution of the DDL entry share it; the fuzzed sub-queries get fresh ids via
setCurrentQueryId("") and are excluded). Removing the fix leaves the counter 0
(the reset never runs), so the assertion flips to 0 and the test fails in every
build mode: release fails on the counter, debug/sanitizer fails on the server
abort.

The assertion query reads system.query_log on a single node, so pin
enable_parallel_replicas = 0 to keep the CI randomizer from turning it into a
distributed read over the parallel_replicas cluster. The test stays parallel
safe (per-query_id attribution, unique ZooKeeper prefix), no no-parallel tag.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…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]>
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]>
…saction-2604-385d

Fix TSAN data race in executeASTFuzzerQueries clearing caller's transaction
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request labels Aug 14, 2026
@robot-clickhouse-ci-2

Copy link
Copy Markdown
Contributor Author

Dear @Algunenano, @groeneai, this cherry-pick PR has not been updated for 3d0h5m5s. Please resolve the conflicts to backport #103158, or close this PR if the backport is no longer needed. This PR will be automatically closed after 7 days of inactivity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants