Skip to content

Fix assertion in selectPartsToMutate for a committed transaction's mutation - #110202

Closed
alexey-milovidov wants to merge 47 commits into
masterfrom
fix-transaction-mutation-restart-83252
Closed

alexey-milovidov wants to merge 47 commits into
masterfrom
fix-transaction-mutation-restart-83252

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

Fixes a LOGICAL_ERROR raised from a background job, and a permanently stuck mutations queue, caused by an orphaned transactional mutation entry.

StorageMergeTree::prepareMutationEntry registers a transactional mutation in the transaction (txn->addMutation) before startMutation registers it in current_mutations_by_version. If KILL TRANSACTION rolls the transaction back between the two steps, the rollback's killMutation sweep finds nothing to remove, and the entry registered afterwards is orphaned: its transaction is gone from the running list and was never committed. The background StorageMergeTree::selectPartsToMutate then raised a LOGICAL_ERROR ("Cannot find transaction ... that has started mutation ... that is going to be applied to part ...") on every scheduling round, and the orphaned mutation stayed pending forever, blocking all subsequent mutations of the affected parts. Found by a fuzzer in the linked issue.

selectPartsToMutate now resolves the state instead of throwing. When the transaction is no longer running and the entry's cached CSN is unknown, it consults TransactionLog::getCSN — the authoritative source, the same check that loadMutations and clearOldMutations use. If the transaction committed, the CSN is cached in the entry and the mutation proceeds. If it never committed, the entry is a rolled-back orphan that nothing else will remove, so it is removed (the same way loadMutations discards entries of uncommitted transactions at startup) instead of blocking the mutations queue.

getIncompleteMutationsStatusUnlocked resolves the same terminal states for waiters: a mutation of a rolled-back or orphaned transaction is reported as killed (unblocking waitForMutation immediately), and a mutation whose transaction committed but is already gone from the running list is checked against the mutation's original snapshot (getVisibleDataPartsVector(tid.start_csn, tid)) — the same visibility gate selectPartsToMutate applies — so the status converges to done and waiters do not hang on parts the mutation was never supposed to touch.

A transaction that is being rolled back is also treated as terminal for its mutations. MergeTreeTransaction::rollback stores Tx::RolledBackCSN before it starts the killMutation sweep, and TransactionLog::rollbackTransaction erases the transaction from the running list only after that sweep returns, so in that window a cancelled transaction is still in the running list. Treating it as pending let selectPartsToMutate schedule a mutate task that killMutation can no longer cancel (it only cancels tasks that are already in MergeList, and MutatePlainMergeTreeTask enters MergeList in prepare), and made the read-only status paths report the cancelled mutation as unfinished, so SELECT ... SETTINGS apply_mutations_on_fly = 1 applied an UPDATE of a transaction that will never commit. tryGetLiveTransactionForMutation now hides an already cancelled transaction from every consumer that only asks whether the mutation is still going to be executed; killMutation keeps using the raw lookup, because it needs the transaction object in exactly that state.

A new pause failpoint mt_start_mutation_pause_before_register holds an ALTER exactly inside the race window, making the orphaned state deterministically reproducible. The new integration test test_kill_transaction_mutation_registration_race fails on an unfixed server (the orphaned mutation stays pending and blocks later mutations) and passes with the fix. A restart smoke test with mutations in implicit transactions is also included. The pause failpoint transaction_rollback_pause_before_kill_mutations holds KILL TRANSACTION inside the rollback window described above, and the integration test test_kill_transaction_mutation_rollback_window asserts there that the cancelled mutation is neither applied on the fly, nor reported as unfinished, nor counted by the table-level mutation counters, nor selected for execution.

Note: #110226 fixes the registration/KILL TRANSACTION race at its source; this change makes the consumer side robust regardless of how the orphan appeared, and turns the previously fatal state into graceful cleanup.

Closes: #83252
Related: #95009
Related: #110226

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

Fix a LOGICAL_ERROR raised from a background job and a permanently stuck mutations queue when a transactional mutation entry outlived its transaction (a race between mutation registration and KILL TRANSACTION): StorageMergeTree::selectPartsToMutate now rechecks the commit state in the transaction log and removes the orphaned mutation entry if the transaction did not commit.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…tation

`StorageMergeTree::selectPartsToMutate` could raise a `LOGICAL_ERROR`
("Cannot find transaction ... that has started mutation ... that is going to be
applied to part ...") and abort the server from a background job when it
encountered a transactional mutation whose transaction was no longer running.
This is especially reachable after a server restart, when no transactions are
running at all, so every still-present transactional mutation is looked up with
`tryGetTransactionForMutation` returning null.

The mutation entry's `csn` field is only an in-memory cache, filled by
`setMutationCSN` on commit and by `loadMutations` on startup. The authoritative
source of whether the transaction committed is the transaction log, which is
exactly what `loadMutations` and `clearOldMutations` already consult via
`TransactionLog::getCSN`. `selectPartsToMutate` now does the same: if the cached
CSN is still unknown it looks the transaction up in the log. If the transaction
is committed, the mutation proceeds without the transaction pointer; if it is
rolled back or otherwise not committed, the part is skipped (the mutation will be
removed by `killMutation` on rollback) instead of aborting.

Added an integration test that runs mutations inside implicit transactions (as
in the original report) and restarts the server, checking it comes back up with
consistent data and no failed or stuck mutations.

Closes: #83252

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d8be011]

Summary: ✅


AI Review

Summary

This PR hardens StorageMergeTree against dead transactional mutation states: orphaned entries left by the registration/KILL TRANSACTION race, rollback-window entries that are already cancelled while still present in the running list, and committed transactional mutations whose on-fly/read-only consumers must respect the original transaction snapshot. On the current head, the scheduler, waiter/status paths, on-fly mutation snapshot, merge predicates, mutation counters, and ALTER prewait logic all appear to handle those states consistently, and the new failpoint-based tests cover the previously reported interleavings with focused regressions. I did not find a remaining correctness issue that warrants a new inline review comment.

Final Verdict

✅ No new blocking issues found in the current revision.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.10% +0.10%

Changed lines: Changed C/C++ lines covered: 213/257 (82.88%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 13, 2026
@tiandiwonder

Copy link
Copy Markdown
Contributor

We tried to verify this on current master and could not reach the UnknownCSN branch through the described scenario: setMutationCSN persists the CSN before the transaction leaves the running list, loadMutations resolves or removes unresolved transactional entries at startup (the restart crash from #83252 was fixed by #95009), and the new integration test also passes without this patch — with implicit_transaction = 1 the commit waits for the mutation to finish, so nothing is pending across the restart.

The only state we found that reaches this branch is a race between mutation registration and KILL TRANSACTION: txn->addMutation runs before the entry is registered in current_mutations_by_version, so a rollback in that window finds nothing to kill and leaves an orphaned entry whose CSN stays unknown forever. We reproduced it deterministically with a pause failpoint: a debug server aborts identically with and without this patch (a chassert in getIncompleteMutationsStatusUnlocked fires first, reached from waitForMutation), and in release builds this patch would postpone the orphaned mutation indefinitely, since nothing ever removes it. #110226 fixes that race at the registration site and adds a failpoint-based regression test that crashes an unpatched debug server.

@tiandiwonder tiandiwonder left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changelog entry describes the restart crash from #83252, but that was fixed by #95009 (the committed-CSN case), and on current master the remaining UnknownCSN throw is not reachable through a restart — details in the discussion comment below.

node.query("DROP TABLE IF EXISTS mt_race_stress SYNC")


def test_mutation_after_restart_does_not_abort(start_cluster):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this test passes without the fix: with implicit_transaction = 1 the commit waits for the mutation to finish (beforeCommit -> waitForMutation), so all 10 mutations are done before the restart and selectPartsToMutate never reaches the changed branch. verified against a build without this patch — all four assertions pass and the Cannot find transaction warning never fires.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right — confirmed and addressed in 065fc00. The docstring now presents this test as a restart smoke test and points to the new deterministic test. The new test_kill_transaction_mutation_registration_race reproduces the orphaned-mutation state (the registration/KILL TRANSACTION race) with a pause failpoint and does fail without the patch: the orphaned mutation stays pending forever and blocks later mutations.

Comment thread src/Storages/StorageMergeTree.cpp Outdated
Comment on lines +1855 to +1864
/// The transaction that started this mutation is no longer running.
/// The mutation entry's `csn` field is only an in-memory cache; it is
/// filled in by `setMutationCSN` on commit and by `loadMutations` on
/// startup. The authoritative source of whether the transaction committed
/// is the transaction log, so consult it if the cached value is still
/// unknown (the same check that `loadMutations` and `clearOldMutations` do).
/// Without this, a mutation whose transaction has committed but whose cached
/// CSN was not updated would raise a spurious `LOGICAL_ERROR` and, in
/// particular, could abort the server via a background job after a restart.
/// See https://github.com/ClickHouse/ClickHouse/issues/83252

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the restart part of this comment doesn't hold: loadMutations already resolves the CSN from the log or removes the uncommitted entry at startup, and on commit setMutationCSN runs before the transaction leaves the running list, so the cache can't be stale for a committed transaction once tryGetTransactionForMutation misses.

Suggested change
/// The transaction that started this mutation is no longer running.
/// The mutation entry's `csn` field is only an in-memory cache; it is
/// filled in by `setMutationCSN` on commit and by `loadMutations` on
/// startup. The authoritative source of whether the transaction committed
/// is the transaction log, so consult it if the cached value is still
/// unknown (the same check that `loadMutations` and `clearOldMutations` do).
/// Without this, a mutation whose transaction has committed but whose cached
/// CSN was not updated would raise a spurious `LOGICAL_ERROR` and, in
/// particular, could abort the server via a background job after a restart.
/// See https://github.com/ClickHouse/ClickHouse/issues/83252
/// The mutation entry's `csn` field is only an in-memory cache and may be
/// stale; the transaction log is the authoritative source, so consult it
/// before deciding (as `loadMutations` and `clearOldMutations` do).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed the comment in bfe495f — thanks. You are right: setMutationCSN assigns the CSN before the transaction leaves the running list and loadMutations resolves/removes entries at startup, so a committed transaction's cached CSN is not stale once tryGetTransactionForMutation misses. The comment now describes the cache/log relationship accurately and characterizes the not-committed case (including the orphaned-entry race that #110226 fixes at the source) instead of the old restart-abort claim.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up: this comment block was reworked once more in 065fc00 — it now describes the terminal-state reasoning (commit caches the CSN before the transaction leaves the running list; rollback erases it only after the killMutation sweep) and the branch itself now removes the orphaned entry instead of skipping it.

Comment thread src/Storages/StorageMergeTree.cpp Outdated
Comment on lines +1869 to +1878
if (mutation_csn == Tx::UnknownCSN || mutation_csn == Tx::RolledBackCSN)
{
/// Transaction is not running but hasn't committed yet - this shouldn't happen
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot find transaction {} that has started mutation {} "
"that is going to be applied to part {}, and mutation CSN is still unknown",
first_mutation_tid, mutations_begin_it->second.file_name, part->name);
/// The transaction was rolled back or is otherwise not committed. Its
/// mutation must not be applied (it will be removed by `killMutation`
/// on rollback); skip the part for now instead of applying a mutation
/// from a transaction that did not commit.
LOG_DEBUG(log, "Mutation {} was started by transaction {} that is not committed (CSN {}), skipping part {}",
mutations_begin_it->second.file_name, first_mutation_tid, mutation_csn, part->name);
current_parts_postpone_reasons[part->name] = PostponeReasons::TRANSACTION_NOT_COMMITTED;
continue;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if the log also returns UnknownCSN here, the transaction is gone from the running list and can never commit, so this skips the same dead mutation on every scheduling round forever — nothing removes it (clearOldMutations only handles finished mutations, and the killMutation mentioned above is exactly what failed to run) and it blocks all later mutations of these parts until a restart. the only way I found to reach this state is the registration race fixed in #110226; with that merged, this branch can keep the exception.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — your analysis is correct. The committed-CSN case is already handled by the cached CSN (set before running_list.erase), and the only state that reaches txn == nullptr && csn == UnknownCSN here is the orphaned mutation left by the mutation-registration/KILL TRANSACTION race, which #110226 fixes at the source. This change is therefore defense-in-depth (turn a LOGICAL_ERROR into a skip) rather than a fix for a path reachable on current master, and skipping such an orphan indefinitely is not clearly better than the exception. Whether to keep this branch as defense-in-depth alongside #110226, or drop it and let #110226 be the sole fix, is left for @alexey-milovidov to decide once #110226 lands. I have not changed the skip-vs-throw behavior in this pass.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 065fc00 — you were right that skipping forever was not acceptable. When the transaction is gone from the running list and the log has no CSN for it, the entry is now removed on the spot (mirroring what loadMutations does with entries of uncommitted transactions at startup): counters are decremented, the entry is erased from current_mutations_by_version, and the mutation_*.txt file is deleted, so it no longer blocks later mutations of the parts. The cached RolledBackCSN case keeps the old skip behavior since killMutation is removing the entry in that window. Additionally, 3bd4eeb makes getIncompleteMutationsStatus report such an entry as killed instead of tripping the txn || isNonTransactional || from_another_mutation assertion, so waitForMutation waiters unblock immediately with the proper "Mutation was killed" error. The new failpoint test covers the whole flow deterministically.

Comment thread src/Storages/StorageMergeTree.cpp Outdated
continue;
}
if (mutation_csn == Tx::UnknownCSN)
mutation_csn = TransactionLog::getCSN(first_mutation_tid);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

optional: write the resolved CSN back to the entry (writeCSN) like loadMutations does.

as-is, a committed-but-stale entry repeats the log lookup on every scheduling round and system.mutations keeps showing no CSN.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 065fc00: when the log lookup finds a committed CSN, it is written back to the entry with writeCSN (under the same mutex that setMutationCSN uses), so system.mutations shows the CSN and subsequent scheduling rounds do not consult the transaction log again.

@tiandiwonder

Copy link
Copy Markdown
Contributor

Since there is no reproducible test case, we can make it as a draft or just close it.

alexey-milovidov and others added 4 commits July 13, 2026 10:55
The previous comment claimed the getCSN fallback prevents a committed
transaction's mutation from aborting the server via a background job
after a restart. That is inaccurate: `setMutationCSN` assigns the
mutation CSN before the transaction leaves the running list, and
`loadMutations` resolves or removes unresolved transactional entries at
startup, so a committed transaction's cached CSN is not stale once
`tryGetTransactionForMutation` misses. Rewrite the comment to describe
what actually happens: the cached CSN may be stale, the transaction log
is authoritative, and the not-committed case (including an orphaned entry
left by a mutation-registration/`KILL TRANSACTION` race, fixed at the
source in #110226) is skipped instead of raising a `LOGICAL_ERROR`.

Per review thread by tiandiwonder on src/Storages/StorageMergeTree.cpp.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address review: the previous behavior of skipping a mutation whose
transaction is gone and uncommitted left the entry in
`current_mutations_by_version` forever. Since mutation selection always
starts from the earliest pending mutation of a part, such an orphaned
entry (left by a race between mutation registration in `startMutation`
and the `killMutation` sweep of a concurrent `KILL TRANSACTION`
rollback) blocked all subsequent mutations of the affected parts until a
restart. Now `selectPartsToMutate` removes the orphaned entry, the same
way `loadMutations` discards entries of uncommitted transactions at
startup, and caches the CSN in the entry when the transaction log shows
the transaction as committed (so `system.mutations` displays it and the
log is not consulted again on every scheduling round).

Add a pause failpoint `mt_start_mutation_pause_before_register` between
the transaction-side and the storage-side mutation registration, and a
deterministic integration test
`test_kill_transaction_mutation_registration_race` that reproduces the
orphaned state with `KILL TRANSACTION`: on an unfixed server the
background job raises a `LOGICAL_ERROR` exception on every scheduling
round and the orphaned mutation stays pending forever; with the fix it
is removed and later mutations proceed. Reframe the previously added
restart test as a smoke test, since it does not exercise this branch.

Related: #83252
Related: #110226

Co-Authored-By: Claude Fable 5 <[email protected]>
…utationsStatus

The assertion `txn || mutation_entry.tid.isNonTransactional() ||
from_another_mutation` in `getIncompleteMutationsStatusUnlocked` assumed
that a transaction can never finish before a mutation it started, which
is exactly the assumption an orphaned mutation entry violates: with the
new deterministic test the waiting `ALTER` polls the orphaned entry and
aborted a debug build on this assertion. Resolve the terminal state of
the transaction instead: if it committed, report the status as usual;
if it never committed, report the mutation as killed (the entry is
either about to be removed by `killMutation`, or is an orphan that
`selectPartsToMutate` removes), which also unblocks `waitForMutation`
waiters immediately with the correct "Mutation was killed" error.

Related: #83252

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@tiandiwonder

Copy link
Copy Markdown
Contributor

#110226 fixes the same race at the source: startMutation re-checks the transaction state under the same lock that registers the entry, so a rollback racing the two registration steps removes the entry immediately and the ALTER fails fast with INVALID_TRANSACTION — the orphaned entry never becomes visible to selectPartsToMutate in the first place. I'd suggest considering that direction first: with the state prevented at the source, the loud LOGICAL_ERROR here keeps its value as a tripwire for genuinely impossible states, rather than being replaced by lazy cleanup that could mask a future producer of the same state.

alexey-milovidov and others added 5 commits July 14, 2026 06:50
…n selectPartsToMutate

The orphan cleanup added in the previous commit ran inside the per-part loop,
after the `isVisible` check. If the earliest pending transactional mutation was
orphaned but every candidate part was invisible to that orphaned snapshot, the
loop hit `continue` at the `isVisible` check and never reached the
`TransactionLog::getCSN` / erase path, so the orphaned entry stayed in
`current_mutations_by_version` and kept blocking all later mutations of those
parts until a restart.

Move the terminal-state resolution of transactional mutation entries into a
part-independent pre-pass at the top of `selectPartsToMutate`: committed entries
get their CSN cached (mirroring `setMutationCSN`), rolled-back entries are left
for the in-flight `killMutation`, and orphaned entries (transaction gone from the
running list and never committed) are removed exactly as `loadMutations` discards
entries of uncommitted transactions at startup. Because orphan detection depends
only on the entry's transaction id and not on any part's visibility, it now runs
regardless of current part visibility. The per-part branch is simplified
accordingly: a still-unknown CSN there only means the transaction became terminal
after the pre-pass in this call, so the part is postponed and rechecked next round.

Related: #83252

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`system.transactions` is global to the server: it lists every running
transaction, not only the paused `ALTER`. The regression test read a bare
`SELECT tid_hash FROM system.transactions` and then asserted the whole table
became empty after `KILL TRANSACTION`, so an unrelated running transaction could
make the test kill the wrong transaction or fail the `count() = 0` assertion even
when the paused `ALTER` was handled correctly.

Snapshot the set of transaction hashes before starting the `ALTER`, identify the
`ALTER`'s own transaction as the single hash that appears afterwards (the
`SYSTEM WAIT FAILPOINT ... PAUSE` handshake guarantees it is already registered),
kill only that hash, and assert that specifically that transaction disappears
rather than that the server-global table empties.

Related: #83252

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…saction

The test identified the paused ALTER's transaction by diffing the
server-global system.transactions before and after starting the ALTER, but
background merge/mutation scheduling begins its own transactions at any
moment, so the diff could match unrelated work: the count() = 1 assertion
could fail intermittently or the test could kill the wrong transaction.

Now the ALTER runs inside an explicit transaction (the race window is
identical to the implicit one from the original report), and the test
captures the transaction's identity with `transactionID()` right after
`BEGIN TRANSACTION`, before the ALTER even starts, then kills exactly that
transaction with `KILL TRANSACTION WHERE tid = ...`. No global-table
diffing remains.

Addresses the AI review Major on #110202

Co-Authored-By: Claude Fable 5 <[email protected]>
…nditional

The AI review pointed out that `SYSTEM ENABLE FAILPOINT` and the explicit
`BEGIN TRANSACTION` ran before the `try`/`finally` cleanup scope in
`test_kill_transaction_mutation_registration_race`: if `BEGIN TRANSACTION`,
`transactionID`, or the sanity assert failed, the test would exit with
`mt_start_mutation_pause_before_register` still enabled and session 42 still
holding an open transaction, poisoning later tests on the module-scoped node.

Now the failpoint enabling and the transaction setup happen inside the `try`,
and the `finally` always disables the failpoint, joins the `ALTER` thread
(it holds the HTTP session lock while running), and detaches or rolls back
the session transaction with a best-effort `ROLLBACK`. `ROLLBACK` on a killed
(rolled-back) transaction only detaches it from the session and does not
throw; when `BEGIN TRANSACTION` never succeeded it throws and is ignored.
Comment thread src/Storages/StorageMergeTree.cpp Resolved
…gainst its snapshot

When the transaction that started a mutation has committed but its object
is already gone from the running list, getIncompleteMutationsStatusUnlocked
fell through to getVisibleDataPartsVector with a null transaction pointer,
which checks the latest active parts instead of the parts visible to the
mutation. A part with a smaller data version committed by another
transaction after the mutation's snapshot is correctly skipped forever by
the visibility gate in selectPartsToMutate, but the status path counted it
and kept returning is_done = false, so waitForMutation could hang even
after the mutation finished every part it was supposed to touch.

Use getVisibleDataPartsVector(mutation_entry.tid.start_csn,
mutation_entry.tid) in that case - the same snapshot the visibility gate in
selectPartsToMutate applies.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110202&sha=00fee23d374acf1b8df967afd9c40b9c4245e1b6&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

01730_distributed_group_by_no_merge_order_by_long failed with Code: 241. MEMORY_LIMIT_EXCEEDED ("would use 513.85 MiB (attempt to allocate chunk of 512.00 MiB), maximum: 100.00 MiB ... While executing AggregatingTransform") on the query that expects no memory limit error with distributed_group_by_no_merge=2. The CI rerun diagnosis passed 138/138 with the same randomized settings, and the CI database shows this test failing ~20–30 times/day over the last two weeks across many job types, including runs on master — a master-side flaky test, unrelated to this PR (transactional mutations). I did not find an existing tracking issue.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 4 commits August 6, 2026 19:57
…n on-fly test

`test_kill_transaction_mutation_orphan_not_applied_on_fly` stopped merges on
the shared node but only ran `SYSTEM START MERGES` and the table drop on the
success path. A failed assertion would leave background merges disabled for
the rest of the `test_transactions` module, so later tests could fail for
unrelated reasons or stop exercising the background cleanup path. The whole
post-setup section is now wrapped in `try`/`finally` that unconditionally
restarts merges and drops the table.

Co-Authored-By: Claude Fable 5 <[email protected]>
The previous guard in MutatePlainMergeTreeTask::executeStep checked
txn->getCSN() == Tx::RolledBackCSN before prepare, but the task only
becomes visible to killMutation's cancelPartMutations sweep when
prepare inserts it into MergeList. A KILL TRANSACTION whose rollback
started between the check and the insertion was missed by both the
check and the sweep, so the task still ran the whole mutate pass and
only threw from MergeTreeTransaction::checkIsNotCancelled at commit.

Move the check into prepare, immediately after the MergeList
insertion (and before the MUTATE_PART_START part log row):
MergeTreeTransaction::rollback stores Tx::RolledBackCSN before the
killMutation sweep, so a rollback that the check misses necessarily
runs its sweep after the insertion and cancels the task through
MergeList.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The three CI reds on cbdda91868e are all unrelated to this PR:

None of them touch the mutation/transaction code paths changed here; a fresh CI run on the new head should clear them.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

Both are mine to answer.

Stress test (amd_debug), install_thread_pool_fault_injection. A fix is already in progress, and it is your own: #113248. I verified the causal link by reading the diff rather than the title. It threads --ast_fuzzer_runs=0 onto the harness's own maintenance queries and keeps a 5-attempt retry around the system.server_settings verification read. That matches this frame exactly: the server-side AST fuzzer runs as a query-finish callback on the connection thread, so that read returns past the client's 15 s receive_timeout and check_output raises CalledProcessError with exit status 159, aborting the job before a single test runs.

Two things worth knowing when keying sightings of this frame. The line number has moved (stress.py:402 now, :291 earlier), so match on the function name plus exit status 159 plus the setting name, not the line. And CIDB cannot see it at all: the stored test_context_raw for these rows is the 20-byte script exit code: 1, so the traceback exists only in the job log. A CIDB-only count of this specific defect reports zero.

Fast test (arm_darwin), 03008_deduplication_diagnostics_opt_in. This one is my regression, not a pre-existing flake, and I will fix it.

The test does not predate the failure: I added it in #112913, merged 2026-08-07, and that merge commit is an ancestor of cbdda91868e, so the failing run did contain it. Its entire failure history in CIDB is those 3 rows, all today, all on Fast test (arm_darwin).

It is a cost timeout rather than a Darwin runner casualty: no Server died row accompanies any of the 3 shas, and all 3 were killed at 60.1 s. Over 8 days it passes everywhere else with headroom (Fast test averages 26.7 s, amd_debug 10.7 s), but on Fast test (arm_darwin) it averages 46.3 s with a p95 of 56.8 s against the 60 s per-test deadline. So it was already in the tail and only that runner crosses the line.

The cost is process spawns, not queries. The test replays all six drivers' failure-handling blocks against stub clients, two phases each, which comes to roughly 10,700 execve plus clone calls. Locally the whole test takes 4.2 s, of which the generator and statement-dump section is 0.9 s, so the driver-replay loop dominates. Process creation on Darwin is far more expensive than on Linux, which explains why only arm_darwin times out.

I will send a separate pull request that cuts that spawn count, rather than raising the timeout or skipping the test, and I will link it here.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

Ask B, the 03008_deduplication_diagnostics_opt_in timeout on Fast test (arm_darwin), as promised:
#113980

Root cause, and it was mine: the test's interrupted-rerun probe keeps its sub-probe inside the probe
directory, and the stub client waits for a go sentinel file by polling. The driver's
wait "$int_pid" returns as soon as the run.sh shell dies from the SIGTERM, but the stub is a
grandchild and is never waited for, so the following rm -rf deletes the sentinel the live stub is
still polling for. It never observes it, spins to its 30 s cap and outlives the test, once per row,
12 times per run. That is 11 to 12 orphaned processes and 1888 to 3686 sleep spawns per run, and it
is where the arm_darwin runner crosses the 60 s deadline, since it already averages 46.3 s there.

The fix replaces both file-sentinel poll loops with blocking bounded reads on FIFOs, so the token
reaches the blocked reader immediately and cannot be deleted out from under it. Orphans go 11-12 to
0, sleep spawns to 0, and total execve from a non-deterministic 2897-4863 to exactly 1189 on
every run. .reference is unchanged. I did not raise the timeout and did not skip the test.

I have no Darwin runner, so the wall-clock gain there is unmeasured from my side and CI on that pull
request is the real measurement.

Ask A, the install_thread_pool_fault_injection timeout, is already answered above: it is
#113248, and nothing is owed from me there.

After the rollback re-check moved into `MutatePlainMergeTreeTask::prepare`
(before the `MUTATE_PART_START` row), an incorrectly selected cancelled
mutation would also leave `system.part_log` empty, so the part_log poll no
longer proved that `selectPartsToMutate` never fired. The loop now also
asserts that the prepare re-check's skip message (which logs the transaction
id, unique to this test) never appears in `system.text_log`, and the part_log
check covers `MutatePartStart` in addition to `MutatePart`. Together they
distinguish "never selected" from "selected but skipped".

Co-Authored-By: Claude Fable 5 <[email protected]>
…ection-level signal

The rollback-window test's evidence (no `MutatePartStart` row and no
prepare-skip line) only proved that `MutatePlainMergeTreeTask::prepare`
never ran for the cancelled mutation: `scheduleDataProcessingJob` can
select the mutation and then drop the task before `prepare` when
`scheduleMergeMutateTask` returns false. `selectPartsToMutate` now logs
a selection message (part, target version, mutation ids, transaction id)
at the only place a mutate task is built, and
`test_kill_transaction_mutation_rollback_window` additionally asserts
that this message never appears in `system.text_log` for the cancelled
transaction. `test_kill_transaction_mutation_task_selected_before_rollback`
pins both the selection and the prepare-skip message wording by asserting
their presence, so the absence assertions cannot silently become vacuous.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
… snapshot

A transactional mutation is applied only to the data parts visible to its
transaction's snapshot: `selectPartsToMutate` skips every other part as
`VERSION_NOT_VISIBLE`, so such a part is never mutated on disk. The on-fly
mutations snapshot (`apply_mutations_on_fly`) stored only the commands of every
pending entry and `MutationsSnapshot::getOnFlyMutationCommandsForPart` decided
purely by comparing the mutation version to the part's data version. So a part
with a smaller data version that was committed by another transaction *after* the
mutation's snapshot still got the `UPDATE`/`DELETE` applied on the fly, returning
data that the mutation never touched and that a plain `SELECT` does not show.

`getMutationsSnapshot` now records, for every transactional entry it puts into the
snapshot, the visibility it is allowed to touch - resolved exactly as
`getVisibleDataPartsVectorForMutationStatus` and the gate in `selectPartsToMutate`
resolve it: the live transaction's snapshot while it runs, and the snapshot
recorded in the entry's transaction id once the transaction is gone (a rolled-back
or orphaned entry is already skipped). `getOnFlyMutationCommandsForPart` skips a
transactional mutation for a part outside that snapshot. Non-transactional
mutations keep applying to every part, so the common path is unchanged;
`getAllUpdatedColumns` deliberately keeps returning the superset, as it only
decides which columns have to be read.

New test `04838_transaction_mutation_on_fly_visibility`: transaction 1 creates a
part, transaction 2 starts and commits a mutation with a larger version, and
transaction 1 commits only afterwards - so its part is invisible to the mutation
and must keep its original value with and without `apply_mutations_on_fly`.
Without the fix the on-fly read returns the mutated value.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110202&sha=702986aef420b1b00b18acf938bf37f9d3844e9d&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

03100_lwu_06_apply_patches failed with a missing patch-3e1a7650697c132eb044cc6f1d82bc92-all_0_0_0_2 15 row in the output; CI's own reproducibility check passed it 3/3 on rerun and labelled it flaky. It is unrelated to this PR (transactional mutations): CIDB shows the same test failing once on the unrelated PR #112378 on 2026-07-30, and nothing in this branch touches lightweight updates or patch parts (the only getMutationsSnapshot change here is a filter that is a no-op for non-transactional mutations). No tracking issue exists yet.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged, investigating. The root cause looks test-side rather than an engine bug, and I will follow up here with a PR.

03100_lwu_06_apply_patches asserts the presence of a patch part that the engine is entitled to drop at that point. MergeTreeData::clearUnusedPatchParts (src/Storages/MergeTree/MergeTreeData.cpp:4501) drops a patch whose getSourcePartsSet().getMaxDataVersion() is <= the minimum data version of the active regular parts in the partition. After ALTER TABLE ... APPLY PATCHES, UPDATE ... the regular parts are at data version 3, so patch-...-all_0_0_0_2 (max source version 2) is genuinely unused and eligible, while patch-...-all_3_3_0_4 (version 4) is not. That asymmetry is exactly what the diff shows: only the _2 row vanished, _4 survived.

The test tries to prevent this with cleanup_delay_period = 1000, but that lever is not sufficient: IMergeTreeCleanupThread::wakeup() is a plain task->schedule(), and there are 12 call sites that bypass the delay (plus wakeupEarlierIfNeeded() on every scheduleDataProcessingJob). So the cleanup can run at any time during the test, which is why it is rare and arm/azure-agnostic.

The fix I intend is the one already used by the sibling tests: pin remove_unused_patch_parts = 0 on the table, as in 03100_lwu_01_basics.sql:16, 03100_lwu_15_future_reads.sh:48 and 03100_lwu_51_condition_evaluated_once.sql:11. I will also check the other tests that assert a literal patch part name without pinning it, so the class is covered rather than the one instance.

On breadth, I agree this is unrelated to this PR. Re-measuring 45 days of CIDB for this test name, the other hits decompose into unrelated causes rather than this signature: the 2026-07-30 hit on #112378 is a Fast test timeout, 2026-07-18 on #110875 and #110567 are default user quota errors, 2026-07-15 on #96886 is a memory limit, and the 2026-07-07 hits are on #103182, which changes patch part sort keys. The only prior hit with this same missing-row shape is #103182, so no tracking issue is warranted separately from the fix.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix: #114135.

Pins remove_unused_patch_parts = 0 and removes the two cleanup_delay_period settings it supersedes, same as #112158 and #100273. Validated in both directions on one provoked state: forcing a cleanup wakeup reproduces exactly this diff with Will drop unused patch part patch-...-all_0_0_0_2 in the log, and the pin makes the same run pass with that line absent.

On the class: I measured data_version for every part in the 9 stateless tests that assert a literal patch-part name, rather than reading the versions off the part names. Only this test and the already-pinned 03100_lwu_01_basics reach patch version <= min active regular version; in the other 7 the minimum stays below every patch version, so I left them alone.

pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Aug 10, 2026
The test lists patch parts after `OPTIMIZE ... FINAL` and asserted a patch part
the engine is entitled to drop at that point, so it intermittently lost the
`patch-...-all_0_0_0_2` row from a `system.parts` listing.

`MergeTreeData::clearUnusedPatchParts` drops a patch once its max source data
version is <= the minimum data version among the partition's active regular
parts. The `ALTER ... APPLY PATCHES, UPDATE` brings that minimum to 3, so from
that point on the patch with version 2 is droppable while the one with version
4 is not. That asymmetry is exactly the observed diff, and it licenses the drop
before all three of the test's part listings, not only the last one. The
`OPTIMIZE ... FINAL` does not lower the minimum, it only merges the two regular
parts into one; with `apply_patches_on_merge = 0` it does not consume the
patches either.

The `cleanup_delay_period = 1000` the test relied on was never a barrier:
`IMergeTreeCleanupThread::start` schedules the first iteration with no delay
(the delay only applies from the second iteration on), and `wakeup` is a bare
`task->schedule` that bypasses the delay from any of its call sites. On
`ReplicatedMergeTree` there is also no further interval gate before the patch
cleanup.

Pin `remove_unused_patch_parts = 0` instead and drop the two superseded delay
settings, matching the existing idiom in `03100_lwu_01_basics` and
`03100_lwu_15_future_reads`. The `.reference` file is unchanged.

Validated in both directions on a single provoked state whose arms differ only
in the pin value: forcing a cleanup `wakeup` between the `OPTIMIZE` and the
final listing reproduces exactly the CI diff together with the
`Will drop unused patch part` log line, and with the pin the same provoked run
passes with that log line absent. 50/50 randomized runs pass.

I measured the data version of every part in the 9 stateless tests whose
`.reference` asserts literal patch-part names. Of those, only this one and the
already-pinned `03100_lwu_01_basics` reach the drop condition, so no other test
is touched. Tests that assert patch state in aggregate rather than by name are
outside that set; `03100_lwu_15_future_reads` and
`03100_lwu_51_condition_evaluated_once` are already pinned.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110202&sha=702986aef420b1b00b18acf938bf37f9d3844e9d&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29
Related: ClickHouse#110202
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

The one flagged item is a -13.8% "improvement" on clickbench Q17, but the change is confined to transactional-mutation and KILL TRANSACTION race handling (mutation selection, rollback windows, the barrier/rename ALTER prewait) plus test-only failpoints. Q17 is a plain read-only GROUP BY SELECT and executes none of that code, so the delta cannot plausibly be caused by this PR and is being read as run-to-run variance rather than a real speedup. Downgraded to not_sure; no other queries moved and no cross-query pattern is present.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 556 479 -13.8% <0.0001 This PR only changes transactional-mutation/KILL TRANSACTION race handling (mutation selection, rollback windows, ALTER prewait). Q17 is a read-only GROUP BY SELECT that never touches those paths, so the -13.8% is run-to-run variance, not a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 56168938-7b2b-4377-9903-9da5d3474134
  • MIRAI run: e19f7055-2c99-4363-8ee6-74a1a699bf21
  • PR check IDs:
    • clickbench_919595_1786549951
    • clickbench_919606_1786549951
    • clickbench_919613_1786549951
    • tpch_adapted_1_official_919626_1786549952
    • tpch_adapted_1_official_919652_1786549951
    • tpch_adapted_1_official_919666_1786549951

alexey-milovidov and others added 2 commits August 11, 2026 22:50
`transactionID()` returns the tuple `(csn, ltid, host_id)` here, but
some builds extend `TransactionID` with extra trailing fields that
appear both in the tuple and in the log-message form of the TID.
Unpacking exactly three fields fails there with `ValueError: too many
values to unpack`. Build the expected log substring from however many
fields the tuple has instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
The prewait scans in `alter` skip transactional mutations that are already
dead when the scan runs, but the chosen mutation can also die during the
wait: `KILL TRANSACTION` rolls back a transactional mutation at any moment,
and its `killMutation` sweep removes the entry, so
`getIncompleteMutationsStatusUnlocked` returns an empty status and
`checkMutationStatus` failed the waiting `ALTER` with
`Mutation ... was killed` - even though the same interleaving a moment
earlier (before the scan) succeeds.

Both prewait branches now loop: `tryWaitForAnotherMutation` returns false
instead of throwing when the mutation was killed or removed during the
wait, and the caller re-scans `current_mutations_by_version` for the
latest mutation that can still be applied. A mutation that dies during
the wait is handled exactly like one that was already dead at scan time.

The new pauseable failpoint `mt_alter_prewait_pause_before_wait` holds the
`ALTER` between the scan and the wait, so the deterministic integration
test `test_kill_transaction_mutation_killed_during_alter_prewait` lands
`KILL TRANSACTION` exactly inside the wait window.
Address review: `test_kill_transaction_mutation_registration_race` never
proved that the orphaned entry was actually created - if the producer
side of the race were closed, the assertions would pass trivially.
Merges are now stopped while the orphan is created, the test asserts
that `system.mutations` holds exactly one entry for the table before
merges are restarted, and then waits for the background mutation
selection to remove that entry (the full entry, not just `is_done = 0`).

Also adds `test_kill_transaction_mutation_killed_during_alter_prewait`,
the deterministic test for the prewait re-scan fix.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The three CI failures on ca7aa1720f64 are unrelated to this PR:

None of the fixes are on master yet, so a re-merge would not clear them; the new push runs fresh CI.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Closing in favor of #110226

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

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Assertion error related to transactions after server restart

3 participants