Skip to content

Fix a concurrent ALTER UPDATE being skipped and reported done in MergeTree - #124167

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
murphy-4o:fix/mutation-skipped-by-unregistered-block
Oct 10, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
murphy-4o:fix/mutation-skipped-by-unregistered-block

Conversation

@murphy-4o

@murphy-4o murphy-4o commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

StorageMergeTree::startMutation takes the mutation's block number before it registers the mutation in current_mutations_by_version. In that window, a mutation registered later with a higher block number could be executed on a part, and a merge could record a mutation version on its result, past the earlier one. The earlier mutation then counted as applied to that part (its data version was above it), its commands never ran there, and mutations_sync reported it done. With 16 concurrent ALTER UPDATE v = v + 1 statements, about half the rounds lost one update.

Mutation selection and the merged part's mutation version now stop at a mutation block that is still being committed and not yet registered, the same way selection already waits for a lightweight update's block.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry:

Fixed a race in MergeTree where an ALTER TABLE … UPDATE or DELETE mutation submitted concurrently with another mutation could be silently skipped on some parts while being reported as done.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.2065-master (included in 26.10 and later)

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f112590]

Summary: ✅


AI Review

Summary

This PR closes the window where a MergeTree mutation has already reserved a block number but is not yet present in current_mutations_by_version, which previously let a later mutation or a merge advance a part past that earlier mutation and then report it as done even though its commands never ran. The fix consistently treats such in-flight mutation block numbers as pending in both mutation selection and merged-part version calculation, and the new stateless test exercises both the later-mutation path and the merge-first path. I did not find a remaining correctness, concurrency, or metadata-versioning issue in the current patch.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit f112590.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Oct 6, 2026
@murphy-4o murphy-4o removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-critical-bugfix labels Oct 6, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Oct 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f112590a5 with master 59c4d18fa (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

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

Job report

@murphy-4o
murphy-4o marked this pull request as ready for review October 6, 2026 10:24
@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes only the background mutation and merge scheduling in plain MergeTree: parts are now postponed while a mutation with a lower block number is still unregistered, and the merged-part version is capped accordingly. No ClickBench or TPC-H SELECT runs this code. All five flagged ClickBench queries (Q16, Q18, Q32, Q33, Q34) stay not_sure, and none needs action. Each is a CPU-bound aggregation that is 6-15% slower; four fall within master's normal range and Q32 has mixed, noisy signals. Two source runs shared one host, which fits this uniform slowdown better than any effect of the diff.

clickbench

⚠️ 5 inconclusive

Flagged queries (5 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 529 584 +10.4% <0.0001 aggregation: This high-cardinality GROUP BY never runs the MergeTree mutation-selection or merge-versioning code this PR changes. The +10.4% is inside master's normal range.
⚠️ 18 not_sure 855 981 +14.7% <0.0001 aggregation: This read-only aggregation does not touch the mutation scheduling paths in the diff. The +14.7% falls within master's normal range, and the measurements are noisy.
⚠️ 32 not_sure 702 789 +12.3% <0.0001 aggregation: The +12.3% is borderline: the two tests disagree and the measurements are very noisy. The PR's mutation and merge changes are not on this SELECT's path.
⚠️ 33 not_sure 1134 1277 +12.6% <0.0001 aggregation: This GROUP BY on a heavy key does not run the changed selectPartsToMutate or getMutationVersionForMergedPart code. The +12.6% is inside master's normal range.
⚠️ 34 not_sure 1123 1192 +6.1% <0.0001 aggregation: The +6.1% is inside master's normal range. This aggregation never executes the mutation-postponement logic added by this PR.

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: d685b7f5-dbe8-4a9a-9585-3ba611a14d37
  • MIRAI run: c25cc3ef-e4f0-4b2a-bc4d-2da1596c529f
  • PR check IDs:
    • clickbench_154446_1791363744
    • clickbench_154558_1791363777
    • clickbench_154665_1791363810
    • tpch_adapted_1_official_154796_1791363848
    • tpch_adapted_1_official_154898_1791363852
    • tpch_adapted_1_official_154998_1791363859

@filimonov

Copy link
Copy Markdown
Contributor

#122934 covered the same + few more cases, and was first. I don't want to waste my time on rebase / fix the branch again.

If you care - please pick & continue the other PR.

lord007tn added a commit to joodlab/logbird that referenced this pull request Nov 11, 2026
* fix(clickhouse): retry deletes skipped by concurrent mutations

Two lightweight DELETEs on the same non-replicated MergeTree table can
allocate mutation versions 50924/50925 but register them in the opposite
order. Parts are then mutated straight to the higher version and the lower
mutation is treated as already applied, so its rows survive while the
mutation reports done (ClickHouse/ClickHouse#124167). The post-delete probe
correctly raised LOGBIRD_DELETE_INCOMPLETE on a non-restored database (#95).

deleteAndVerify now re-issues the DELETE with a fresh mutation version up to
three times, logging clickhouse.delete_retry, and still throws the unchanged
error when rows stay visible, so restored parts that outrank every new
mutation (#75/#77) keep failing closed. It is exported and tags every
statement as project maintenance; sample-data removal, event-index repair and
the operator scripts now use it instead of unverified DELETEs.

Closes #95

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(selfhost): link the ClickHouse upgrade that fixes the mutation race

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(clickhouse): address delete-retry review findings

- deleteAndVerify takes the project id explicitly, logs
  {level, event: clickhouse.delete_retry}, and its exhausted error carries
  table/attempts and tells operators to retry before the restore procedure.
- repairEventIndex writes valid pointers first; a stale-pointer delete that
  stays visible is reported (clickhouse.event_index_stale_pointers), not
  thrown, so restored parts cannot stall exclusive ingest recovery.
- demo-clean's activity delete runs under the workspace project lock and its
  header no longer claims every delete goes through purgeProject.
- The namespace migration re-runs its ALTER UPDATEs until no row matches.
- Drop the export benchmark's redundant event_ids delete; restore the identity
  benchmark, which must keep running on older checkouts.
- Tests use fake timers; concurrency cleanup errors no longer mask failures.
- Add an opt-in stress test (LOGBIRD_MUTATION_RACE_STRESS=1, never in CI) for
  the out-of-order mutation race on a throwaway table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(clickhouse): stress test owns its table and needs an idle mutation pool

Plain CREATE TABLE so a leftover or concurrent table is never adopted, drop
only the table this run created, require zero unfinished mutations elsewhere
before starting, and abort if any appear between rounds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(scripts): verify the identity benchmark event_ids cleanup

A bounded delete/probe loop with the existing client, so older checkouts
without deleteAndVerify still run, and a skipped mutation cannot leave
orphan pointers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(clickhouse): address round-3 delete-retry review findings

- deleteAndVerify documents that callers hold the exclusive project lock and
  rejects params.p that disagrees with projectId; its tagging is now tested
  with an untagged client.
- repairEventIndex skips the empty insert again.
- The restore cutover gate also blocks on
  clickhouse.event_index_stale_pointers, and the docs name the new warning and
  sample-data removal failing closed.
- demo-clean's header says the activity delete keeps event_ids pointers and
  receipts; the namespace migration logs each re-run.
- The stress test bounds LOGBIRD_MUTATION_RACE_ROUNDS to 1-20 and tolerates
  non-JSON warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(clickhouse): address round-4 delete-retry review findings

- deleteAndVerify requires the predicate to start with project_id={p:String}
  and params.p to equal projectId, so it is project-scoped by construction;
  unit tests cover the rejections, the empty-insert guard and a clean
  stale-pointer delete without a warning.
- Stress test: 20 s statement cap (client and server), no round starts
  after 150 s, a cleanup reserve inside a 330 s timeout, the round bound is
  validated inside the gated test, and a cleanup failure fails an otherwise
  passing run.
- Restore gate: stale-pointer warnings need investigation (ineffective
  normalization is one cause), and a delete retry during the gate requires a
  system.parts/system.mutations check before cutover.
- demo-clean: explain why kept receipts are harmless.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(clickhouse): bound the stress test with absolute deadlines

Statements are capped at 10 s; no round or DELETE burst starts after 150 s
(the deadline is rechecked right before the burst), so the worst round ends
by ~250 s; cleanup polls pending mutations only until 275 s, leaving DROP
and client close inside the 330 s timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(clickhouse): build the project scope inside deleteAndVerify

A prefix check accepted "project_id={p:String} AND a OR b", which ClickHouse
parses as a cross-project delete. deleteAndVerify now takes only a filter and
builds `project_id={p:String} AND (filter)` itself, binding p to projectId
and rejecting a caller-supplied p. Callers pass filters; unit tests cover the
parenthesized OR filter, the 50/100 ms backoff and a purge that continues
after a second-attempt success. The lock docstring now distinguishes scoped
deletes from whole-project script purges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(selfhost): exact restore-gate version check for delete retries

Compare only mutated parts (data_version > max_block_number) with the newest
mutation created during the gate, because plain inserted parts naturally
outrank older mutations; the delete_retry grep triggers that check instead
of blocking by itself. The stress test notes that its idle guard needs the
admin user.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(clickhouse): address round-6 delete-retry review findings

- The restore-gate version check is a runnable step (expanding heredoc,
  clickhouse-client --queries-file, parseDateTimeBestEffort) that runs for
  every table with a gate mutation; a delete_retry match is informational.
- Stress test: one socket per concurrent DELETE (max_open_connections) and a
  header budget that matches the code (burst start <= 150 s, end ~220 s).
- demo-clean defines its activity filter once for the count and the delete;
  the lock docstring covers every caller with live writers.
- Unit test pins the exact cutoff DELETE and its bound params; two
  integration fixtures delete event_ids through deleteAndVerify.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(clickhouse): address round-7 delete-retry review findings

- Restore gate: select mutated parts with data_version > min_block_number so
  merged mutated parts count, and block a table that has mutated parts but no
  gate mutation instead of skipping it. Add the delete_incomplete grep.
- deleteAndVerify rejects read() date-rewritten param keys so the DELETE and
  its probe always bind the same values.
- Log clickhouse.delete_incomplete once before every fail-closed throw; the API
  maps it to a retryable 503 without time-range advice.
- Stale-pointer error test now proves valid pointers are written first.
- Document deleteAndVerify in the package README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(clickhouse): address round-8 delete-retry review findings

- deleteAndVerify takes { logIncomplete }; the non-fatal stale-pointer cleanup
  logs only its own warning, so delete_incomplete means a fail-closed delete.
- The verification probe gets a 60 s budget: a filter outside the sort key
  (sample-data source) scans the whole project once nothing matches.
- Restore gate counts only finished gate mutations, and states its
  mutation-version assumption with a link to #77.
- Note why a partial sample-data skip cannot strand anything that matters.
- The identity benchmark's local verify loop backs off and logs its retries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(clickhouse): address round-9 delete-retry review findings

- The verification probe runs through ch.query with exactly the DELETE's
  params and a 60 s budget, so a timeout is a retryable 503 rather than a
  422 query-budget error; the read() date-key guard is no longer needed.
- The stress test clamps every statement back to its 10 s server cap.
- Restore gate shows pending gate mutations; docs name the callers that log
  delete_incomplete; README lists the options argument.
- purgeProject builds its cutoff params once instead of stripping p twice.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(clickhouse): address round-10 delete-retry review findings

- A storage error or timeout after a DELETE ran (probe, or a retry DELETE)
  fails closed as LOGBIRD_DELETE_UNVERIFIED with the cause, logs
  clickhouse.delete_unverified, and maps to a retryable 503 without
  time-range advice. A first-DELETE error still propagates unchanged.
- The delete-failure HTTP mapping is a pure module tested in CI's
  no-services server unit config.
- The samples crash fixture deletes raw rows through deleteAndVerify.
- The namespace migration's update retries back off and log JSON.
- The restore-gate version check covers only the five deleted tables, and
  its grep includes delete_unverified.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(clickhouse): address round-11 delete-retry review findings

- A first DELETE that times out or is cancelled (ClickHouse 159/394, or a
  client timeout/abort/reset) may still run as a mutation: fail closed as
  LOGBIRD_DELETE_UNVERIFIED. Definite rejections still propagate unchanged.
- Restore gate docs say how to clear a block after a transient cause.
- deleteFailureResponse ignores inherited object keys; the app wiring is
  tested for both delete codes; the README notes DELETE_ATTEMPTS.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
filimonov pushed a commit to Altinity/ClickHouse that referenced this pull request Nov 21, 2026
…date of it is uncommitted

A mutation could pick a part while a lightweight `UPDATE` with a lower block number had not
written its patch part yet; the mutated part then skipped the patch and the acknowledged update
was lost. This branch needs it as the base of ClickHouse#124167 (lost lightweight `DELETE` in CI).

Upstream: ClickHouse#119155
Upstream merge commit: 72006b7
Commits of the upstream pull request:
- 8a53df6 Merge remote-tracking branch 'origin/master' into mergetree-mutation-pending-patch-116686
- 7638e85 Tag `05227_mutation_waits_for_lightweight_update` as `no-fasttest`
- d9f77ec Merge remote-tracking branch 'origin/master' into mergetree-mutation-pending-patch-116686
- 4398d33 Wake up the postponed mutation and make the test deterministic
- cf21123 Merge remote-tracking branch 'origin/master' into mergetree-mutation-pending-patch-116686
- ea880f9 Merge branch 'master' into mergetree-mutation-pending-patch-116686
- 8db4dc2 Leave a part alone while a lightweight update of it is uncommitted

Adaptation for antalya-26.8:
- None: applied as is.

(cherry picked from commit 72006b7)

Signed-off-by: Mikhail Filimonov <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
filimonov pushed a commit to Altinity/ClickHouse that referenced this pull request Nov 21, 2026
…ed and reported done in MergeTree

A mutation takes its block number before it is registered. A part mutated in that window
moved past the unregistered version, so its commands were never applied while the mutation
reported done. Seen here as an acknowledged lightweight `DELETE` lost in CI
(`cas_lightweight_delete`): mutation 16 registered before mutation 15.

Upstream: ClickHouse#124167
Upstream merge commit: 9355332
Commits of the upstream pull request:
- f112590 Do not skip a mutation that has its block number but is not registered yet

Adaptation for antalya-26.8:
- `src/Storages/StorageMergeTree.cpp`, `StorageMergeTree::getMutationVersionForMergedPart`:
  hunk dropped. The function and `isMaterializedByMerge` do not exist on this branch: a merge
  here never records a mutation version above its source parts.
- `05331_mutation_not_skipped_before_registration`: kept as is. Both cases, including
  "a merge materializes the DROP COLUMN first", fail without this change and pass with it.

(cherry picked from commit 9355332)

Signed-off-by: Mikhail Filimonov <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants