Skip to content

Fix TSAN data race in executeASTFuzzerQueries clearing caller's transaction - #103158

Merged
Algunenano merged 14 commits into
ClickHouse:masterfrom
groeneai:fix-tsan-race-astfuzzer-transaction-2604-385d
Jul 7, 2026
Merged

Algunenano merged 14 commits into
ClickHouse:masterfrom
groeneai:fix-tsan-race-astfuzzer-transaction-2604-385d

Conversation

@groeneai

@groeneai groeneai commented Apr 20, 2026 •

Copy link
Copy Markdown
Collaborator

The server-side AST fuzzer (executeASTFuzzerQueries, active only when ast_fuzzer_runs > 0) used to clear the transaction on the caller's query and session Context with no lock held:

context->getQueryContext()->getSessionContext()->setCurrentTransaction(NO_TRANSACTION_PTR);
context->setCurrentTransaction(NO_TRANSACTION_PTR);

Context::setCurrentTransaction writes merge_tree_transaction unsynchronized, while other threads read the same field under the shared Context::mutex via Context::createCopy. Under RESTORE ASYNC with ast_fuzzer_runs > 0, RestorerFromBackup background 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 on Stress test/BuzzHouse (experimental, serverfuzz, *_tsan)).

Fix

  1. Move the transaction reset onto the fuzz session-context copy, so the caller context is never mutated.
  2. Skip fuzzed BACKUP/RESTORE queries. An async backup/restore returns from executeQuery immediately while BackupsWorker keeps the (fuzz) context alive for background workers that read it via Context::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 across ast_fuzzer_runs > 0) and 04305_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_runs CI/stress-test setting, never a production user path, so this is categorized as a CI fix.

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Backported to: 26.6.4.16

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

a) Deterministic repro?
Yes. BEGIN TRANSACTION; INSERT ... ; SELECT ... SETTINGS ast_fuzzer_runs = 3; INSERT ... ; COMMIT; fails on the pre-patch binary with Code: 649. INVALID_TRANSACTION: There is no current transaction on the final COMMIT. The pattern is captured as tests/queries/0_stateless/04104_ast_fuzzer_preserves_caller_transaction.sql.

b) Root cause explained?
executeASTFuzzerQueries at executeQuery.cpp:2111-2113 (before this patch) called setCurrentTransaction(NO_TRANSACTION_PTR) on the caller's query and session Context. Context::setCurrentTransaction writes merge_tree_transaction without holding any lock. Context::createCopy reads all ContextData fields (including merge_tree_transaction) under SharedLockGuard(other->mutex). When RESTORE ASYNC (or any background task) is running and still calling Context::createCopy on the caller's query context, the ASTFuzzer finish callback on the TCP handler thread races with those readers — TSAN flags the shared_ptr<MergeTreeTransaction> read-during-assignment race observed in STID 2604-385d.

c) Fix matches root cause?
Yes. The reset is moved onto the fuzz session context COPY (after makeSessionContext), which only the current thread can observe. The parent Context is no longer touched. This also incidentally fixes a latent correctness bug — the previous behaviour silently cleared the user's active transaction whenever the finish callback fired with ast_fuzzer_runs > 0.

d) Test intent preserved?
Yes. Fuzzed queries still see no inherited transaction: fuzz_session_context is copied from context, then its merge_tree_transaction is cleared, then fuzz_context is copied from the already-cleared fuzz_session_context. The fuzz context chain is identical to before; only the parent-context mutation is removed.

e) Both directions demonstrated?
Yes. On the pre-patch binary the regression test fails with INVALID_TRANSACTION on COMMIT. On the patched binary it passes 10/10 runs with --no-random-settings and 10/10 runs with the default CI randomization (modulo the server-config-dependent async_insert=1 issue that also affects existing transaction tests when run outside the full CI test config).

f) Fix is general, not a narrow patch?
The fix is narrow by design — it only touches the executeASTFuzzerQueries path because that is the only unsafe caller of setCurrentTransaction on a shared context (other callers operate on newly created single-threaded contexts or on the session/query context during the synchronous execution of BEGIN/COMMIT/ROLLBACK). A defensive-locking follow-up in setCurrentTransaction/getCurrentTransaction would make the API self-safe, but is not required to close this race. I opted not to bundle that here to keep the diff minimal and the fix targeted.

Session: cron:clickhouse-ci-task-worker:20260420-131500

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 executeASTFuzzerQueries that moves the transaction reset from the caller's shared Context onto the fuzz session context copy. First master hit on 2026-04-20 (STID 2604-385d). The PR body has the full TSAN report and the code path analysis.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Apr 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1388c1f]

Summary: ✅


AI Review

Summary

This PR moves the AST fuzzer's transaction cleanup off the caller Context, skips fuzzed BACKUP/RESTORE queries that can leak the fuzz context into background work, and skips the redundant replicated-database DDL re-fuzz path that was still inheriting a live ZooKeeperMetadataTransaction. I re-checked the current head against the full PR diff, the prior inline discussion, and the current code paths in executeQuery, DDLWorker, DatabaseReplicated, and the added regressions. I did not find a remaining correctness issue that still warrants an inline finding.

Final Verdict

✅ No new findings. The previously reported issues appear resolved in the current head.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 20, 2026
@tavplubix

Copy link
Copy Markdown
Member

Other
threads concurrently read that same field from the same Context under the shared
Context::mutex via Context::createCopy (SharedLockGuard(other->mutex) at
Context.cpp:1299). The scenario that triggers the race in CI is RESTORE ASYNC

@groeneai, this reminds me of #92103 which fixed a crash that was happening for a similar reason

2. ?
3. ?
4. ?
5. ?
6. ?
7. ?
8. ./ci/tmp/build/./contrib/llvm-project/libcxx/src/mutex.cpp:29: std::mutex::lock()
9. ./ci/tmp/build/./src/Server/HTTP/WriteBufferFromHTTPServerResponse.cpp:166: DB::WriteBufferFromHTTPServerResponse::onProgress(DB::Progress const&)
10. ./ci/tmp/build/./src/Interpreters/executeQuery.cpp:571: DB::flushQueryProgress(DB::QueryPipeline const&, bool, std::function<void (DB::Progress const&)> const&, std::shared_ptr<DB::QueryStatus>)
11. ./ci/tmp/build/./src/Interpreters/executeQuery.cpp:597: DB::logQueryFinishImpl(DB::QueryLogElement&, std::shared_ptr<DB::Context> const&, std::shared_ptr<DB::IAST> const&, DB::QueryPipeline&&, bool, std::shared_ptr<DB::OpenTelemetry::SpanHolder>, DB::QueryResultCacheUsage, bool, std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<long long, std::ratio<1l, 1000000l>>>)
12. ./contrib/llvm-project/libcxx/include/__functional/function.h:610: ?
13. ./ci/tmp/build/./src/Interpreters/executeQuery.cpp:2046: DB::executeQuery(DB::ReadBuffer&, DB::WriteBuffer&, bool, std::shared_ptr<DB::Context>, std::function<void (DB::QueryResultDetails const&)>, DB::QueryFlags, std::optional<DB::FormatSettings> const&, std::function<void (DB::IOutputFormat&, String const&, std::shared_ptr<DB::Context const> const&, std::optional<DB::FormatSettings> const&)>, std::function<void ()>)
14. ./ci/tmp/build/./src/Interpreters/SharedDatabaseCatalog.cpp:4669: DB::SharedDatabaseCatalog::tryExecuteDDLQuery(std::shared_ptr<DB::IAST> const&, std::shared_ptr<DB::Context const>, DB::QueryFlags)
15. ./ci/tmp/build/./src/Interpreters/InterpreterCreateQuery.cpp:1941: DB::InterpreterCreateQuery::createTable(DB::ASTCreateQuery&)
16. ./ci/tmp/build/./src/Interpreters/InterpreterCreateQuery.cpp:2788: DB::InterpreterCreateQuery::execute()
17. ./ci/tmp/build/./src/Databases/DatabasesCommon.cpp:584: DB::DatabaseWithOwnTablesBase::createTableRestoredFromBackup(std::shared_ptr<DB::IAST> const&, std::shared_ptr<DB::Context>, std::shared_ptr<DB::IRestoreCoordination>, unsigned long)
18. ./ci/tmp/build/./src/Databases/DatabaseShared.cpp:574: DB::DatabaseShared::createTableRestoredFromBackup(std::shared_ptr<DB::IAST> const&, std::shared_ptr<DB::Context>, std::shared_ptr<DB::IRestoreCoordination>, unsigned long)
19. ./contrib/llvm-project/libcxx/include/__functional/function.h:610: ?
20. ./contrib/llvm-project/libcxx/include/future:1438: std::__packaged_task_func<std::function<std::future<void> (DB::RestorerFromBackup::schedule(std::function<void ()>&&, char const*)::$_0&&, Priority)> DB::threadPoolCallbackRunnerUnsafe<void, DB::RestorerFromBackup::schedule(std::function<void ()>&&, char const*)::$_0>(ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true>>&, String const&)::'lambda'(DB::RestorerFromBackup::schedule(std::function<void ()>&&, char const*)::$_0&&, Priority)::operator()(DB::RestorerFromBackup::schedule(std::function<void ()>&&, char const*)::$_0&&, Priority)::'lambda'(), std::allocator<std::function<std::future<void> (DB::RestorerFromBackup::schedule(std::function<void ()>&&, char const*)::$_0&&, Priority)> DB::threadPoolCallbackRunnerUnsafe<void, DB::RestorerFromBackup::schedule(std::function<void ()>&&, char const*)::$_0>(ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true>>&, String const&)::'lambda'(DB::RestorerFromBackup::schedule(std::function<void ()>&&, char const*)::$_0&&, Priority)::operator()(DB::RestorerFromBackup::schedule(std::function<void ()>&&, char const*)::$_0&&, Priority)::'lambda'()>, void ()>::operator()() (.7da09f4b4720e497129bd63a126ceece)
21. ./contrib/llvm-project/libcxx/include/future:1752: std::packaged_task<void ()>::operator()()
22. ./ci/tmp/build/./src/Common/ThreadPool.cpp:799: ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true>>::ThreadFromThreadPool::worker()
23. ./contrib/llvm-project/libcxx/include/__functional/function.h:610: ?
24. ./ci/tmp/build/./src/Common/ThreadPool.cpp:809: ThreadPoolImpl<std::thread>::ThreadFromThreadPool::worker()
25. ./contrib/llvm-project/libcxx/include/__thread/thread.h:201: void* std::__thread_proxy[abi:ne190107]<std::tuple<std::unique_ptr<std::__thread_struct, std::default_delete<std::__thread_struct>>, void (ThreadPoolImpl<std::thread>::ThreadFromThreadPool::*)(), ThreadPoolImpl<std::thread>::ThreadFromThreadPool*>>(void*)
26. ?
27. ?

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?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@tavplubix, thanks for the cross-link. You're right, this is the same architectural problem.

The three known instances share one root: RestorerFromBackup schedules async work that copies query_context (the HTTP handler's per-query context). Per-query state that the HTTP handler set there outlives the request and dangles in the async workers:

  • progress_callback (pointing at WriteBufferFromHTTPServerResponse::onProgress): fixed in PR Fix crash in WriteBufferFromHTTPServerResponse::onProgress() for async restore started via HTTP protocol #92103 for the OSS createDatabase and createTable paths via setProgressCallback(nullptr) at RestorerFromBackup.cpp:523 and :787. Your new stack goes through DatabaseShared::createTableRestoredFromBackup -> SharedDatabaseCatalog::tryExecuteDDLQuery -> executeQuery (Cloud-only code), so the OSS nullptr is bypassed there. I can't read the private code, but the symptom matches: that path is running executeQuery on a context whose progress_callback still points at the dead WriteBufferFromHTTPServerResponse.
  • current_transaction (the MergeTreeTransaction shared_ptr): this PR, narrow scope. executeASTFuzzerQueries was writing NO_TRANSACTION_PTR to the caller's query_context and its session_context, racing with Context::createCopy in restore workers (read side, STID 2604) and itself producing the write-side TSan reports (STID 3336).
  • Probably more (query_finish_callback, process_list_elem, ...).

I agree with the architectural direction PR #92103's own TODO calls out: "Get rid of using query_context in class RestorerFromBackup." Concretely, a Context::createCopyForBackgroundWork helper that strips all HTTP-bound state in one place, called once at the top of RestorerFromBackup, would prevent further instances of this class instead of fixing each field in each call site.

PR #103158 is still useful as a targeted fix for the executeASTFuzzerQueries write race: the AST fuzzer should not be touching the caller's transaction regardless of the broader restore fix. The corruption also fires in non-restore paths (any HTTP query with ast_fuzzer_runs > 0 silently clears the caller's active transaction today, which is a latent correctness bug the new test 04104_ast_fuzzer_preserves_caller_transaction pins).

Do you prefer:

  1. Land this PR as the narrow fix and I file a follow-up issue plus PR for the Context::createCopyForBackgroundWork refactor in RestorerFromBackup?
  2. Or fold the refactor into this PR?

Either way I'm happy to drive it. The Cloud SharedDatabaseCatalog::tryExecuteDDLQuery bypass of PR #92103's progress_callback nullptr would still need a separate Cloud-side patch on top.

@tavplubix

Copy link
Copy Markdown
Member

@groeneai try addressing the root cause because, as you mentioned, similar issues seem to be possible in other places

Comment thread src/Interpreters/executeQuery.cpp Resolved
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]>
@groeneai

groeneai commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator Author

@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 Context after it has been handed to async backup/restore work. In production, once a user's RESTORE ASYNC returns, the HTTP handler finishes and nothing further mutates merge_tree_transaction; only executeASTFuzzerQueries re-executes mutated copies of the just-finished query and then clears the transaction on the context that may have escaped to BackupsWorker background workers. The clickhouse-gh bot independently flagged this on the inline thread.

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 BACKUP/RESTORE queries entirely in the fuzzer. That removes the only place a context is mutated post-escape, and fuzzing backup/restore has negligible value anyway since there is no real backup target.

The pre-existing PR #92103 pattern (progress_callback, and the Cloud SharedDatabaseCatalog path that bypasses its OSS fix) is a separate, genuinely architectural item. I think the clean long-term fix there is a Context::createCopyForBackgroundWork helper that strips all HTTP-bound state (progress/finish callbacks, process list element, transaction) at the RestorerFromBackup/BackupsWorker boundary, used once instead of nulling each field per call site. Happy to file that as a follow-up if you agree it belongs separately from this fuzzer fix.

Validation in both directions on an ASan build:

  • skip removed: fuzzer re-executes async BACKUP/RESTORE and escapes to background workers
  • skip present: zero fuzzed BACKUP/RESTORE queries; 04305_ast_fuzzer_skips_backup_restore and 04104_ast_fuzzer_preserves_caller_transaction pass

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

Heads up on a CI-contract issue, not a real failure: Bugfix validation (functional tests) fails on the new 04305_ast_fuzzer_skips_backup_restore test, while 04104_ast_fuzzer_preserves_caller_transaction passes.

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 04305 can only assert "server alive + restored rows intact", which a release binary satisfies pre-fix too. So the pr-bugfix contract cannot be satisfied for a sanitizer-only race. PR #103692 hit the same gap recently.

The entire change lives in executeASTFuzzerQueries, gated on the ast_fuzzer_runs stress-test/CI setting and never reachable on a production user path. I have recategorized the PR from Bug Fix to CI Fix or Improvement (changelog entry is not required), which is the accurate category.

@tavplubix could you drop the pr-bugfix label so the Bugfix-validation job stops gating? Fork contributors cannot remove labels (RemoveLabelsFromLabelable is denied for me).

Session: cron:clickhouse-ci-task-worker:20260604-013100

alexey-milovidov and others added 2 commits June 28, 2026 18:53
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
@clickhouse-gh clickhouse-gh Bot added pr-ci and removed pr-bugfix Pull request with bugfix, not backported by default labels Jun 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 44f7661

Every 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 CH Inc sync is exempt.

Check / test Reason Owner
Stress test (all sanitizer variants) + BuzzHouse (amd_msan) / STID 3729-* Cannot add ZooKeeper operation because query is executed flaky / trunk: the server-side AST fuzzer re-fuzzes a replicated DDL on a live ZooKeeperMetadataTransaction (addOp abort via DatabaseReplicated::commitAlterTable). The identical diff ran clean for 24 days; this surfaced only after merging current master, and also fires on 2 unrelated PRs (0 master) a fix task is investigating at full effort (root cause known: the fuzzer does not clear metadata_transaction; fix-approach decision pending with the subsystem owner; fixing-PR link to follow here)
Stateless tests (arm_binary, parallel) / 03518_alter_logical_race flaky (chronic; 15+ unrelated PRs + 3 master / 30d) #108060 (external, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log (background-mutation CANNOT_PARSE_TEXT 'x' as UInt64) flaky (chronic upgrade-check log noise; 0 master / ~50 unrelated PRs) #108563 (ours, open)
Mergeable Check / PR — rollups of the above, no distinct failure
CH Inc sync — CH Inc sync (private, not actionable)

None PR-caused: this PR's diff is executeASTFuzzerQueries (skip async BACKUP/RESTORE) plus two fuzzer regression tests, unrelated to all three failure classes.

Session id: cron:our-pr-ci-monitor:20260629-043000

pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Jul 1, 2026
…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]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (test-strengthening for 04339, HEAD 40ebd9c) (click to expand)
# Question Answer
a Deterministic repro? Yes. ALTER ... SETTINGS ast_fuzzer_runs=5, ast_fuzzer_any_query=1 on a table in a Replicated database deterministically drives the fuzzer into the DDLWorker re-execution and increments ASTFuzzerClearedMetadataTransaction (observed 5/5 per run). Disabling resetZooKeeperMetadataTransaction() deterministically leaves it 0.
b Root cause explained? The fuzzed replicated DDL inherits the caller's live ZooKeeperMetadataTransaction; moveOpsTo/addOp on the already-executed txn throws Cannot add ZooKeeper operation because query is executed. The fix detaches metadata_transaction on the fuzz context copy. The old 04339 asserted only server liveness, which a release build satisfies without the fix because that LOGICAL_ERROR is caught inside executeASTFuzzerQueries (Exception aborts only in debug/sanitizer).
c Fix matches root cause? This change is test-only: it asserts the detach directly via the ASTFuzzerClearedMetadataTransaction ProfileEvent (added with the fix), attributed to the ALTER by initial_query_id, so the regression is caught independent of build mode rather than relying on a crash.
d Test intent preserved / new tests added? Preserved and strengthened. Keeps the alive liveness line and adds a positive counter assertion; no assertion weakened.
e Both directions demonstrated? Yes. With fix: 20/20 pass with randomization, counter non-zero. Strip disabled (env-gated rebuild, then fully reverted, Build ID restored to 9b714daad7): persisted query_log shows counter 0 for the ALTER and the test fails (release path fails on the counter, debug fails on the abort).
f Fix is general across code paths? N/A (test-only change; the underlying code fix and its call-site scope were validated in the prior commit 068d04c).
g Fix generalizes across inputs? N/A (test-only change).
h Backward compatible? N/A (test-only change; adds no setting/format).
i Invariants and contracts preserved? Yes. Test stays parallel safe (per-query_id attribution, unique ZooKeeper prefix, no no-parallel); enable_parallel_replicas = 0 is pinned only on the single-node system.query_log introspection so the randomizer cannot turn it into a distributed read.

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

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (04339 Style + flaky-check fix, HEAD 02ccd89) (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-test 04339_ast_fuzzer_replicated_ddl_metadata_transaction FAILS the reference diff on every run before the fix (extra s1 r1 OK 0 0 rows), matching the CI flaky-check diff exactly (2 rows before alive, 1 after). Style: check_style/various_checks.sh flags the missing current_database = currentDatabase().
b Root cause explained? Two PR-caused defects in the new test. (1) Style: the system.query_log assertion lacked the mandatory current_database = currentDatabase() condition. (2) Flaky-check FAIL: the replicated CREATE TABLE / fuzzed ALTER / DROP TABLE ... SYNC run in the default distributed_ddl_output_mode = throw, which prints a per-replica status row (s1 r1 OK 0 0) to stdout that is not part of the checked output.
c Fix matches root cause? Yes. (1) Add AND current_database = currentDatabase() to the query_log query. (2) Pin distributed_ddl_output_mode = none on every DDL invocation (ddl="${CLICKHOUSE_CLIENT} --distributed_ddl_output_mode=none"), so no status rows reach stdout.
d Test intent preserved / new tests added? Preserved. The ASTFuzzerClearedMetadataTransaction > 0 assertion still fires: the client (initial) row carries the counter and runs in the current database, so scoping by initial_query_id + currentDatabase() still yields a positive delta (verified: raw sum 10 -> 5 with the db filter, still > 0). The alive liveness check and the detach contract are unchanged.
e Both directions demonstrated? Yes. WITHOUT the DDL-output fix: FAIL (the s1 r1 OK 0 0 rows leak, reproducing the CI diff). WITH the fix: 30/30 pass with randomization + flaky-check mode; companion 04305 unchanged (3/3).
f Fix is general across code paths? N/A (test-only fix; no source change, Build ID unchanged).
g Fix generalizes across inputs? Both CI variants covered: repl-db variant (db = currentDatabase()) and dedicated-rdb variant (db = rdb_<db>) both pass; the counter row is present in both and the DDL output is silenced in both.
h Backward compatible? N/A (test-only).
i Invariants and contracts preserved? Yes. distributed_ddl_output_mode = none only suppresses stdout status rows; it does not change DDL execution or the metadata-transaction detach the test verifies. The ASTFuzzerClearedMetadataTransaction counter is orthogonal to DDL output mode (verified the counter still fires with the flag on the ALTER).

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

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 776eaf0 — replaces the metadata_transaction detach (068d04c) with a root-cause fix: skip the AST fuzzer entirely when an internal replicated-DDL execution is in flight.

The detach fixed STID-3729 (Cannot add ZooKeeper operation because query is executed) but only moved the abort: with the txn 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). commitCreateTable/dropTable/renameTable/detachTablePermanently sit on the same invariant. Skipping the redundant DDLWorker re-fuzz covers both sites at once and leaves those assertions intact as real invariants. The initiating client query is still fuzzed normally.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Debug build + embedded Keeper + a Replicated database: fuzzing ALTER TABLE t MODIFY COLUMN ... SETTINGS ast_fuzzer_runs = 15, ast_fuzzer_any_query = 1 aborts the server (pre-fix binary, Build ID fea11e66) at iteration 1. Server log: `Logical error: '!ddl_worker
b Root cause explained? DatabaseReplicatedDDLWorker re-executes a committed DDL entry with QueryFlags{.internal=false} on a context that has is_replicated_database_internal=true and a live single-shot ZooKeeperMetadataTransaction. The finish-callback fuzzer fires again on that context. 068d04c detached the txn to avoid the 3729 addOp, but is_replicated_database_internal makes shouldReplicateQuery() return false, so a fuzzed ALTER runs locally via StorageMergeTree::alter → DatabaseOrdinary::alterTable → DatabaseReplicated::commitAlterTable, where getZooKeeperMetadataTransaction()==nullptr while ddl_worker is active → the line-2435 chassert fails (STID-3817).
c Fix matches root cause? Yes. The real defect is that the fuzzer re-fires during internal DDL log replay at all. The fix returns early from executeASTFuzzerQueries when is_replicated_database_internal or a live metadata txn is present — addressing the mechanism, not a symptom. It replaces the detach (which was a symptom-guard that merely moved 3729 → 3817) and removes the now-dead Context::resetZooKeeperMetadataTransaction helper.
d Test intent preserved / new tests added? Yes. 04339 (added in this PR) now asserts the new contract build-mode-independently: ASTFuzzerSkippedReplicatedDDLInternal > 0, attributed by initial_query_id. It still exercises the exact replicated-DDL re-fuzz path. 04305 (BACKUP/RESTORE skip) and 04104 (transaction preserve) are unchanged and unaffected (they reference only ASTFuzzerSkippedBackupRestore/ASTFuzzerQueries).
e Both directions demonstrated? Yes. Pre-fix binary (Build ID fea11e66, detach + no guard): aborts at commitAlterTable:2435 (STID-3817) on the fuzzed ALTER. Fixed binary (Build ID 7d1db97b): 04339 passes 10/10, server survives, ASTFuzzerQueries=5 (client-side fuzzing preserved) + ASTFuzzerSkippedReplicatedDDLInternal bumped on the internal-replay row; 04305 output matches its reference.
f Fix is general across code paths? Yes. The guard sits at the single fuzz entry point (executeASTFuzzerQueries), so it protects every downstream commit path — commitAlterTable, commitCreateTable, dropTable, renameTable, detachTablePermanently — that shares the ddl_worker-active ⇒ txn invariant, not just the one commitAlterTable site CI happened to hit. It also subsumes STID-3729 (the addOp site), since the fuzzer no longer runs on the entry's live transaction at all.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The guard keys on context state (is_replicated_database_internal / presence of a metadata transaction), independent of the fuzzed query kind, its column datatypes/wrappers, ALTER command type, or DB/table engine. Any DDL replayed by the replicated DDL worker takes the early return regardless of the specific fuzzed AST.
h Backward compatible? Yes. No setting default, on-disk/wire/replication format, or user-visible behavior changes. The only observable change is that the server-side AST fuzzer no longer re-fuzzes during internal replicated-DDL log replay (a debugging aid, not a product contract) and a renamed internal ProfileEvent (ASTFuzzerClearedMetadataTransaction → ASTFuzzerSkippedReplicatedDDLInternal). No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes — strengthened. The invariant "on a live Replicated DB, a metadata commit while ddl_worker is active must carry a ZooKeeperMetadataTransaction" (commit* chasserts) is now upheld rather than bypassed: the fuzzer never reaches those commit paths on an internal context. Client-path fuzzing is unchanged. No lock/ownership contract touched.

Session id: cron:clickhouse-worker-slot-1:20260702-010300

@groeneai

groeneai commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 776eaf0

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel, 2/2) / 03040_dynamic_type_alters_2_compact_merge_tree flaky (TSAN timing; renamed-Dynamic values lost after ALTER RENAME COLUMN in compact parts; 10 unrelated PRs + 1 master in 45d, unrelated to this PR's fuzzer-context diff) #104822 (ours, open, approved)
Stress test (arm_tsan) / Possible deadlock on shutdown (see gdb.log) hung-check shutdown-deadlock family (chronic trunk; ~20 unrelated PRs + master in 14d; the arm_tsan job itself is green) #108212 (ours, merged) / #105905 (ours, merged)
Sync — CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260702-073000

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, as all fixes have been merged, please update the branch.

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov Branch updated: merged current master (afd09cf) into the PR branch, now at 1388c1f. Clean merge, no conflicts, PR scope unchanged (8 files, +268/-8). CI is re-running on the up-to-date base.

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.80% +0.00%

Changed lines: Changed C/C++ lines covered: 30/30 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1388c1f

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
(none) CI fully finished on this head with no test or job-level failures —
CH Inc sync — CH Inc sync (private, not actionable)

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 Algunenano left a comment

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.

I don't like the solution, but I couldn't find anything better

@Algunenano
Algunenano added this pull request to the merge queue Jul 7, 2026
Merged via the queue into ClickHouse:master with commit fbac517 Jul 7, 2026
175 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 7, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov could you apply v26.6-must-backport to this PR? 26.6 is still aborting on the
race it fixes, and per your 2026-07-27 note on #111910 I am routing the label request through you
rather than hand-authoring the backport.

Two TSAN hits, both 26.6, both after this merged:

ref fix present signature
master yes none since 2026-07-07
26.7 a728f669 yes none since 2026-07-07
26.6 dc7e750e no ThreadSanitizer: data race (STID: 3336-2c6d) (report)
26.6 via #114310 no same STID (report)

The reported frames are Context::setCurrentTransaction at Context.cpp:7557 from
executeASTFuzzerQueries at executeQuery.cpp:2114. On 26.6, line 2114 is the bare
context->setCurrentTransaction(NO_TRANSACTION_PTR) on the caller context that this PR deletes;
on 26.7 and master only the fuzz_* clears remain. CIDB agrees: the signature fired 73 times
across 48 PRs in the 90 days before the merge and exactly twice since, both on 26.6, zero on
master, 26.7, 26.5, 26.3 and 25.8. Stress coverage on 26.6 and 26.7 is comparable over the last
30 days, so 26.7's zero is a real negative.

The label expands to 26.7 and 26.6. 26.7 already contains fbac5176, so the cherry-pick there
resolves to an empty diff and is skipped; only 26.6 gets a PR.

The port conflicts, so it will come out as a pr-cherrypick PR. The conflict is one hunk, the
ProfileEvents extern block: keep ASTFuzzerSkippedBackupRestore and
ASTFuzzerSkippedReplicatedDDLInternal, drop QueryParseMicroseconds, which does not exist on
26.6. ProfileEvents.cpp merges clean. With that resolution both caller clears are gone and all
four new symbols land, so the port is not half-inert. The two regressions found during review here
were fixed inside this PR before merge, so nothing has to ride along.

26.5 and 26.3 carry the same pre-fix lines but have not reproduced the signature in 90 days;
25.8 has no server-side fuzzer. I am not asking for labels for those.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 14, 2026
robot-ch-test-poll added a commit that referenced this pull request Aug 24, 2026
Cherry pick #103158 to 26.6: Fix TSAN data race in executeASTFuzzerQueries clearing caller's transaction
robot-clickhouse added a commit that referenced this pull request Aug 24, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 24, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 24, 2026
Backport #103158 to 26.6: Fix TSAN data race in executeASTFuzzerQueries clearing caller's transaction
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…uzzer-transaction-2604-385d

Fix TSAN data race in executeASTFuzzerQueries clearing caller's transaction
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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-ci pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants