Skip to content

Fix a server abort when a transaction is rolled back during stack unwinding - #120929

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-txn-rollback-terminate-unwinding
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-txn-rollback-terminate-unwinding

Conversation

@groeneai

@groeneai groeneai commented Sep 18, 2026 •

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):

Fixes a server crash that can happen when an error causes an open transaction to be rolled back, for example when a background merge or mutation fails on a table used in a transaction. Only affects servers with allow_experimental_transactions enabled.

Description

Found by the AST fuzzer, which aborted the server with std::terminate (STID 2631-4bbd). Provenance, the fatal stack and the validation runs are in the details block below; the carrier PR touches no transaction code.

TransactionManager::rollbackTransaction is noexcept so that destructors can call it, but its opening LOG_TRACE asked for the in-flight exception's code whenever std::uncaught_exceptions() was non-zero. getCurrentExceptionCode() is a bare throw;, legal only while an exception is being handled. A non-zero std::uncaught_exceptions() means the opposite: one is in flight and no handler has been entered, which is exactly when __cxa_rethrow calls std::terminate(). The guard selected the illegal case and skipped the legal one. Wrapping the call cannot help, because __cxa_rethrow terminates directly rather than throwing, and nothing can retrieve the in-flight exception during unwinding anyway. So I drop the code from the message and keep the rest. Nothing is lost: every execution that reached that call either terminated the server or printed an already-handled exception's code.

Besides the fuzzer, this aborted the server on any throw inside background merge or mutation scheduling for a transactional table, because BackgroundJobsAssignee::threadFunc is a function-try-block whose handler is entered only after the transaction holder has been unwound.

Not a recent regression: the line is present in 26.3 to 26.8 and in tags back to v22.7. Reachable only with allow_experimental_transactions enabled.

The new failpoint is the only way to reach the path from SQL. Happy to drop it and the test if you consider it noise, and equally happy to drop the executeQuery.cpp comment change, which only removes a description of the code this PR deletes.

I also noticed one latent but currently unreachable sibling (ExceptionKeepingTransform::onException through StorageAlias.cpp, whose callback vector is provably empty on that path). No user input reaches it, so I am not raising it.

Provenance, fatal stack and validation
SELECT check_name, commit_sha, count() FROM default.checks
WHERE test_name = 'Received signal -1 (STID: 2631-4bbd)' AND check_start_time > now() - INTERVAL 90 DAY
GROUP BY ALL
-- AST fuzzer (amd_debug, targeted, old_compatibility)  1652fe2d258b4d758e40a92a444130f3d3e1fdf9  1

First occurrence in 90 days, on the STID key and on position(test_context_raw, 'MergeTreeTransactionHolder::onDestroy') > 0 alike. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118490&sha=1652fe2d258b4d758e40a92a444130f3d3e1fdf9&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

abort <- terminate_handler() <- std::terminate() <- __cxa_rethrow
  <- DB::getCurrentExceptionCode()                     Common/Exception.cpp:578
  <- DB::TransactionManager::rollbackTransaction(...)  TransactionManager.cpp:633
  <- DB::MergeTreeTransactionHolder::onDestroy()       MergeTreeTransactionHolder.cpp:69
  <- ~MergeTreeTransactionHolder()                     MergeTreeTransactionHolder.cpp:46
  <- DB::ContextData::~ContextData()   (a fuzz Context released while unwinding)

onDestroy skips its autocommit branch precisely when std::uncaught_exceptions() != 0, so the aborting path is the one this noexcept rollback exists to serve. MergePlainMergeTreeTask::txn_holder is a third carrier.

Validated on a debug build. Without the fix the new test kills the server (runner return code: 210, process SIGABRT, log Terminate called without an active exception, frames 3 to 13 identical to the report). With it, 50 consecutive randomized runs pass and the server logs the surviving message microseconds before the assignee's handler reports the injected exception. With the failpoint disabled, or with the transactional insert skipped, the asserted witness is absent, so it is keyed to the injected throw.


Workflow [PR]
Sync PR [sync-upstream/pr/120929]

…inding

TransactionManager::rollbackTransaction is noexcept and exists to be callable
from destructors. Its opening LOG_TRACE asked for the in-flight exception's
code whenever std::uncaught_exceptions() was non-zero:

    LOG_TRACE(log, "Rolling back transaction {}{}", txn->tid,
              std::uncaught_exceptions() ? fmt::format(" due to uncaught exception (code: {})",
                                                       getCurrentExceptionCode()) : "");

getCurrentExceptionCode() is a bare rethrow (try { throw; } catch (...) in
src/Common/Exception.cpp), which per [except.throw]/9 is legal only while an
exception is presently being *handled*. The two states are tracked by different
counters in the Itanium ABI: __cxa_rethrow reads __cxa_eh_globals::caughtExceptions,
populated by __cxa_begin_catch, while std::uncaught_exceptions() reads
uncaughtExceptions, incremented by __cxa_throw and decremented by
__cxa_begin_catch. So a non-zero std::uncaught_exceptions() means an exception
is in flight and no handler has been entered yet, which is exactly when
caughtExceptions is null and __cxa_rethrow calls std::terminate() directly. The
guard selected the one case in which the call is illegal, and skipped the case
in which it would have been legal (inside a handler, where the counter has
already been decremented and the suffix was therefore never printed).

Wrapping the call in try/catch is not a fix: __cxa_rethrow
(contrib/llvm-project/libcxxabi/src/cxa_exception.cpp) calls std::terminate()
itself rather than throwing, so no handler can intercept it. Nothing can
retrieve the in-flight exception at that point either; during phase-2 unwinding
the exception object is reachable only from the personality routine, and
std::current_exception() reads the same caughtExceptions slot, so it is null
there too. Drop the code from the message and keep the part that is knowable.
Nothing is lost: every execution that reached the call either terminated the
server or, in the nested case, reported the already-handled exception's code
rather than the in-flight one, so the "(code: N)" suffix never once conveyed a
correct value from this call site.

Three live carriers reach the aborting path. MergeTreeTransactionHolder::onDestroy
skips its autocommit branch precisely when std::uncaught_exceptions() is non-zero
and falls through to rollbackTransaction, so the destroyed-while-unwinding path
is the one the noexcept rollback exists to serve:

  * StorageMergeTree::scheduleDataProcessingJob holds a local
    MergeTreeTransactionHolder across metadata and part selection whenever the
    table has transactions_enabled, and its caller
    BackgroundJobsAssignee::threadFunc is a function-try-block whose catch (...)
    is entered only after that holder has been unwound, so any throw in
    background merge or mutation scheduling on a transactional table aborted the
    server;
  * a Context holding an open transaction whose last reference is released while
    an exception unwinds, which is how the AST fuzzer reached it;
  * MergePlainMergeTreeTask::txn_holder, destroyed with the task object.

executeQuery.cpp's hoisted fuzz-context declarations carried a comment
describing the removed code; it is replaced with the reason that survives.

The failpoint is how the path is reached from SQL: of the three carriers only
background scheduling is drivable by a query, and nothing in that function
throws today. It is REGULAR rather than ONCE so that a tick on another table
cannot consume it, and it is modelled on the FAULT_INJECTED failpoints already
in the same file.

Measured on a debug build (clang-22, the ci/defs/defs.py ToolSet pin). With the
failpoint present and the log line unchanged, the new test kills the server and
the fatal stack matches the CI report frame for frame: abort <- terminate_handler
<- std::terminate <- __cxa_rethrow <- getCurrentExceptionCode <-
rollbackTransaction <- MergeTreeTransactionHolder::onDestroy <- ~holder <-
scheduleDataProcessingJob <- BackgroundJobsAssignee::threadFunc, reported as
"Terminate called without an active exception". With the fix the same test
passes 50 consecutive randomized runs, the server logs the surviving message on
that path microseconds before the assignee's handler reports the injected
exception, and the transaction is rolled back.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings;
bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test can pass without the background transaction ever being rolled back, so it does not prove the unwinding rollback path (05229_txn_rollback_during_unwinding_no_terminate.sh:52-79) DISAGREE The witness is not reachable without the rollback. The injected throw is inside the lifetime of the holder (StorageMergeTree.cpp:2242-2247) and the only handler is BackgroundJobsAssignee::threadFunc's function-try-block one frame out, so the holder is destroyed before the handler logs; onDestroy returns early only for a null or non-running transaction, and this one was just begun. Measured on the same test file: without the fix it aborts with rollbackTransaction at frame 11 of a stack identical to the report's frames 3 to 13; with the fix the rollback message is logged 9.7 ms before the handler's line, which is what shows the rollback ran during unwinding. The suggested system.transactions_info_log witness is measured inverted rather than corroborating: every background tick on a transactional table begins and rolls back a transaction, so the failpoint-off arm recorded 23 Rollback rows against the baseline's 0.
2 💡 Bug Fix is selected although a process-terminating abort belongs under Critical Bug Fix DISAGREE I do not select Critical Bug Fix on my own initiative. Bug Fix (user-visible misbehavior in an official stable release) is also accurate: the identical statement is present in 26.3 to 26.8 and in tags back to v22.7. The body states the reachability caveat (allow_experimental_transactions), so please re-label it if you read it as critical.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-48:20260918-222100

@clickhouse-gh clickhouse-gh Bot closed this Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, in about 2 seconds: create a MergeTree table, BEGIN TRANSACTION; INSERT ... SETTINGS async_insert = 0; COMMIT, SYSTEM ENABLE FAILPOINT mt_throw_after_background_transaction_begin, insert once more. The server is gone. Not a probabilistic repro.
b Root cause explained? Yes. std::uncaught_exceptions() != 0 means an exception is in flight; a bare throw; needs one to be being handled. The Itanium ABI tracks the two with different counters (uncaughtExceptions vs caughtExceptions), so the guard on that LOG_TRACE selected exactly the state in which __cxa_rethrow calls std::terminate(), and skipped the state in which the call would have been legal.
c Fix matches root cause? Yes: the wrong predicate's call site stops asking for a value that provably cannot exist there. No widened bound, no size reduction, no tag, no defensive wrapper. A try/catch around the call would be the band-aid, and it does not even work: __cxa_rethrow calls std::terminate() directly instead of throwing.
d Test intent preserved / new tests added? New stateless test 05229_txn_rollback_during_unwinding_no_terminate.sh, with a mutation arm, a negative control and a precondition control. No existing test weakened, shortened or retagged.
e Both directions demonstrated? Yes, with the same test file. Pre-fix binary: runner return code: 210, server SIGABRT, log Terminate called without an active exception, frames 3 to 13 identical to the CI report. Post-fix binary: 50 of 50 consecutive randomized runs pass, and the fixed statement's own message is observed on that path microseconds before the assignee's handler logs the injected exception.
f Fix is general across code paths? Yes, fixed at the source rather than guarded at the crash site, so all three carriers are covered by the one statement: the background scheduling holder (tested), a Context released during unwinding (the fuzzer path), and MergePlainMergeTreeTask::txn_holder. Re-run on the final tree, grep -rn -B2 -A2 uncaught_exceptions --include=*.cpp --include=*.h src/ | grep getCurrentException returns nothing, where it previously returned exactly this line. The other 38 std::uncaught_exceptions() uses are chassert, branch or safeExit decisions that never bare-rethrow.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers do not apply: the change removes one fmt::format argument from a log statement and has no data-typed input. The dimension that does exist is the exception state, and all three are covered: in flight (fixed and tested), inside a handler (the suffix was already empty, unchanged), none (unchanged).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, so no SettingsChangesHistory.cpp entry; no format, protocol or ABI change. The only observable difference is one LOG_TRACE line losing a (code: N) suffix it never printed correctly from this site, plus one new opt-in failpoint name.
i Invariants and contracts preserved? Yes. The function stays noexcept and now honours it on the unwinding path; LockMemoryExceptionInThread, the component guard, txn->rollback() and everything after it are untouched. getCurrentExceptionCode()'s precondition is now respected rather than redefined, so no other caller is affected. The failpoint throws before any merge is registered, so the holder rolls the transaction back and threadFunc's catch (...) calls postpone(), which is the pre-existing error path and was observed taking effect.

Session id: cron:clickhouse-impl-slot-5:20260918-213900

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [731db53]

Summary: ✅


AI Review

Summary

This PR removes an invalid getCurrentExceptionCode call from the shared TransactionManager::rollbackTransaction path, which is reachable from destructor-driven rollback during stack unwinding and could terminate the server instead of completing the rollback. The added stateless regression test now keys its witness to the exact table name, so it no longer accepts log rows from unrelated transactional MergeTree tables on a reused server. I did not find a remaining correctness or coverage issue in the current code.

Missing context / blind spots
  • ⚠️ I did not run the new stateless test locally. The current GitHub checks show Fast test, Style check, Build (arm_tidy), and Config Workflow passing, while the main build matrix and the aggregate PR check were still pending when I reviewed.
Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 731db53.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d46c7ae

Every failure below has an owner: a fixing PR (mine 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
Build (arm_tidy) master-side clang-tidy break: error: duplicate include [readability-duplicate-include] on src/Core/tests/gtest_settings.cpp, failing unit_tests_dbms.dir/Core/tests/gtest_settings.cpp.o. Not from this branch: 53 distinct PRs and true master carry the identical error between 18:26Z and 00:26Z. It entered master at 17:34Z when two PRs that each added #include <IO/VarInt.h> at a different position of the same block merged without a textual conflict (mine #118612 was one of them) #120930 (external, merged 2026-09-18 23:19:51Z), merged master @ d8606d3ed1418
Finish Workflow / Post Hooks consequential, not an independent failure: new_tests_check.py reports both Bugfix validation (functional tests, amd64/aarch64) jobs as DROPPED (Dropped due to previous failure [Build (arm_tidy)]), so no per-arch job could report OK or XFAIL #120930 (external, merged), merged master @ d8606d3ed1418
Mergeable Check, PR praktika rollups of the two rows above (Failed: Workflow Post Hook, Build (arm_tidy), Dropped: 149), no independent failure #120930 (external, merged), merged master @ d8606d3ed1418
Sync - CH Inc sync (private, not actionable by me)

Rule 3c, not 3d, decided at the tree that ran: praktika pins the merge commit at run creation, and the
failing run 35403725359 was created at 2026-09-18T22:57:06Z, before the revert merged at 23:19:51Z, so that tree could
not contain the fix. The revert is now on this branch (d8606d3ed1418), where gtest_settings.cpp carries a
single IO/VarInt.h include again. My own change is byte-identical across the merge (unchanged
git patch-id) and the merge brings no submodule or other content change. CI is re-running on d8606d3ed1418.

Session id: cron:our-pr-ci-monitor:20260919-020058

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 731db532b with master 0a7853b2b (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

The failpoint the regression test uses is server wide: while it is enabled,
every transactional MergeTree table that runs BackgroundJobsAssignee::threadFunc
throws the same exception, and the assignee reports it under the same logger
name (__PRETTY_FUNCTION__), so a witness row could not be attributed to the
table the test drives. Measured on a server holding one extra transactional
table: the old witness fires for a table whose transactions_enabled is false,
i.e. one that cannot reach the failpoint at all.

With the table in the message, the test matches text_log's message_format_string
and value1 columns, which keep the exception's format string and its arguments,
so the table is compared exactly instead of as a substring of the rendered
message. Measured with the same fixture plus a same-database table whose name
extends t_txn_unwind: the witness is set only when this test's own table
traversed the path. 50/50 runs pass on the polluted server (the extra table
emitted 6 of its own witness rows during that batch), and with the rollback fix
reverted the test still fails with the abort.
@tuanpach tuanpach self-assigned this Sep 19, 2026
@tuanpach

Copy link
Copy Markdown
Member

@groeneai can simplify the change log entry?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Simplified, the entry now reads:

Fixes a server crash that can happen when an error causes an open transaction to be rolled back, for example when a background merge or mutation fails on a table used in a transaction. Only affects servers with allow_experimental_transactions enabled.

Down from 469 to 253 characters, present tense, with the mechanism left in the description. Body edit only, no code change.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3a23261

Every failure below has an owner: a fixing PR (mine 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
Performance Comparison (arm_release, master_head, 5/6) measurement shard, not a regression of this diff, which touches only the transaction rollback path: the job-level summary is 10 errors, 3 too long, 1 unstable, while 1362 of the 1364 per-query rows on the shard are success and the other 2 are unstable. The shard is trunk-wide red since 2026-09-18, master-side too: reds per day on true master are 0 up to and including 09-16, then 1 on 09-17, 10 on 09-18 and 4 so far on 09-19. In the last 24 hours the shard failed on 156 distinct pull requests #120923 (external, open)
Mergeable Check, PR praktika rollups of the row above, no independent failure of their own #120923 (external, open)

The three other rows of the previous ledger are green at this head: Build (arm_tidy),
Finish Workflow and its post hook all pass now that the revert #120930 is an ancestor of this
branch, and CH Inc sync reports pass on this run.

Session id: cron:our-pr-ci-monitor:20260919-110331

@murphy-4o

Copy link
Copy Markdown
Member

@groeneai i think my fix is better: #122891 , if you agree, please close your PR

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, #122891 is the better fix: it makes getCurrentExceptionCode(), getCurrentExceptionMessage() and tryLogCurrentException() safe to call when no exception is being handled, so it covers this rollbackTransaction call site and any other caller of those helpers, while this PR only changes the one call site and needs a new failpoint to test it.

The only hunk here that yours does not carry is the comment above fuzz_session_context in executeQuery.cpp. It says getCurrentExceptionCode() only works inside a catch handler, which stops being true with your change, so you may want to update it there.

I'm fine with closing this PR in favour of yours, and I'll leave the close to you or @ tuanpach, who approved this one.

@tuanpach

Copy link
Copy Markdown
Member

Close in favor of #122891

@tuanpach tuanpach closed this Sep 30, 2026
@clickhouse-gh clickhouse-gh Bot added comp-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
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-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... 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.

4 participants