Skip to content

Add mutation completion time finish_time in system.mutations - #105255

Closed
foadfbf wants to merge 6 commits into
ClickHouse:masterfrom
foadfbf:add-finish-time-system-mutations
Closed

foadfbf wants to merge 6 commits into
ClickHouse:masterfrom
foadfbf:add-finish-time-system-mutations

Conversation

@foadfbf

@foadfbf foadfbf commented May 18, 2026 •

Copy link
Copy Markdown

Resolves #89216

This change adds a new finish_time column, which is set when a mutation completes and remains zero for unfinished mutations. For non-replicated MergeTree tables, the finish time is persisted in the mutation entry file so it survives table reloads. It is backward compatible without old mutation entry files that do not have this field; zero is used as the default value for old mutation files.

For ReplicatedMergeTree tables, finish_time is persisted in Keeper under <replica_path>/mutation_finish_times/<mutation_znode> aka one child per mutation. The child is created atomically alongside the mutation_pointer update in ReplicatedMergeTreeQueue::tryFinalizeMutations when the mutation is marked done. On startup, the server reads the per-mutation finish times together with the mutation entries and assigns them on MutationStatus, so every mutation in system.mutations reports its real completion time after a restart. Old mutation entry files that do not have this field are set to the default value of zero. The change also cleans up the newly added keys as well as per-mutation finish time keys in the Keepr properly.

Accordingly, a column is added to StorageSystemMutations, and documentation is updated. Since the mutation file parser has been changed for local non-replicated tables, tests are added to verify correct parsing and serialisation.

Stateless tests are added for non-replicated and replicated tables to verify unfinished mutations with zero finish_time, correct value for finish time after mutation completion, and persistence of finish_time across SYSTEM RESTART REPLICA for replicated tables.

For cluster-level completion time across replicas, aggregate per-replica rows as follows:

SELECT
    mutation_id,
    max(finish_time) AS finish_time
FROM system.mutations
WHERE database = 'db' AND table IN ('replica_1', 'replica_2')
GROUP BY mutation_id;

Changelog category (leave one):

  • New Feature

Changelog entry (a [user-readable short description]:

Add finish_time column to system.mutations that records when a mutation is completed; unfinished mutations report 0.


Note

Medium Risk
Adds new persisted metadata for mutation completion across both local and replicated MergeTree engines, including new Keeper znodes and mutation finalization/cleanup logic; mistakes could misreport status or leak znodes/files.

Overview
system.mutations now exposes a new finish_time DateTime column, reporting when a mutation completed (or 0 while unfinished), and documentation/reference outputs are updated accordingly.

For non-replicated MergeTree, mutation entries persist completion time by appending finish time: to mutation_*.txt, updating the parser to tolerate optional tail fields in any order (and error on unknown fields), and marking no-work mutations as finished immediately.

For ReplicatedMergeTree, per-replica completion timestamps are persisted in Keeper under replica_path/mutation_finish_times/<mutation>, loaded on startup, updated atomically when finalizing mutations, and cleaned up alongside old mutation entries; new unit/stateless/integration tests validate unfinished/finished behavior and persistence across restarts.

Reviewed by Cursor Bugbot for commit bf293a3. Bugbot is set up for automated code reviews on this repo. Configure here.

@CLAassistant

CLAassistant commented May 18, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@foadfbf
foadfbf marked this pull request as draft May 18, 2026 17:11
Issue: [Add finish_time to system.mutations](ClickHouse#89216)

This change add a new `finish_time` column, which is set when a mutation completes
and remains zero for unfinished mutations. For non-replicated `MergeTree` tables,
the finish time is persisted in the mutation entry file so it survives table reloads.
It is backward compatible without old mutation entry files that do not have this field;
zero is used as the default value for old mutation files.

For `ReplicatedMergeTree` tables, `finish_time` is persisted in Keeper under
`<replica_path>/mutation_finish_time`, written alongside `mutation_pointer` when
`ReplicatedMergeTreeQueue::tryFinalizeMutations` marks the mutation as done. On restart,
`finish_time` is restored from Keeper, so `system.mutations` reports the original
completion time rather than the restart time. Different replicas can finish the same
mutation at different times, so `finish_time` reflects the local replica's completion time.

Accordingly, a column is added to `StorageSystemMutations`, and documentation is
updated. Since the mutation file parser is changed for local non-replicated tables,
tests are added to verify correct parsing and serialisation.

Stateless tests are added for non-replicated and replicated tables to verify unfinished
mutations with zero `finish_time`, correct value for finish time after mutation
completion, and persistence of `finish_time` across `SYSTEM RESTART REPLICA` for replicated tables.

For cluster-level completion time across replicas, aggregate per-replica rows as follows:

```
SELECT
    mutation_id,
    max(finish_time) AS finish_time
FROM system.mutations
WHERE database = 'db' AND table IN ('replica_1', 'replica_2')
GROUP BY mutation_id;

```
@foadfbf
foadfbf force-pushed the add-finish-time-system-mutations branch from 9864655 to 58feb54 Compare May 18, 2026 20:39
@foadfbf
foadfbf marked this pull request as ready for review May 19, 2026 06:54
@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label May 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5b213c6]

Summary: ✅


AI Review

Summary

This PR adds finish_time to system.mutations and persists it through local mutation files and per-replica Keeper nodes for ReplicatedMergeTree. The feature shape is useful, but the current patch still has correctness problems around transactional local mutation parsing and retry/failure paths for persisting completion time, so I do not think it is ready to merge.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeMutationEntry.cpp:153] [dismissed by author -- https://github.com/Add mutation completion time finish_time in system.mutations #105255#discussion_r3292554367] MergeTreeMutationEntry must preserve the old transactional state semantics for existing local mutation files, but the parser now initializes csn to Tx::NonTransactionalCSN before reading optional tail fields. A file with tid but no csn used to retain the member default Tx::UnknownCSN; now loadMutations skips the uncommitted-transaction check because !entry.csn is false, so a mutation from an uncommitted transaction can be kept and executed after restart. Keep csn as Tx::UnknownCSN after reading tid unless a csn: field is present, and only use Tx::NonTransactionalCSN when there is no tid.

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeMutationEntry.cpp:122] writeFinishTime mutates the in-memory finish_time before the append, finalize, and sync succeed. If any of those operations throws, markFinishedMutationsUnlocked can retry with a non-zero in-memory value, skip the append, and later mark the mutation done without persisting the timestamp. Assign finish_time only after the durable write succeeds, or reset it on exception so retries persist it.
  • [src/Storages/StorageMergeTree.cpp:963] Legacy local mutation_*.txt files that predate this feature do not contain a real completion timestamp, but markFinishedMutationsUnlocked writes time(nullptr) the first time they are observed as done. That stores observation/upgrade time, not mutation completion time, contradicting the PR contract that old files default to zero. Keep legacy missing finish_time as 0, for example by distinguishing "field absent" from "current-format unfinished".
  • [src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp:2615] [dismissed by author -- https://github.com/Add mutation completion time finish_time in system.mutations #105255#discussion_r3292535653] tryFinalizeMutations still is not timestamp-idempotent across an uncertain Keeper multi result. The current code uses unconditional set with version -1 for mutation_finish_times/<mutation>; if the first multi commits at t1 but the client loses the response, the retry at t2 overwrites the already-persisted finish time and then stores t2 in memory. Use a no-overwrite write strategy, a version-checked transition from the pre-created empty node, or reload the existing persisted value on retry instead of overwriting it with retry time.
Tests
  • ⚠️ Add a focused parser/load regression for a local mutation file with tid and no csn, proving it remains Tx::UnknownCSN and follows the uncommitted-transaction handling path.
  • ⚠️ Add Keeper retry/fault-injection coverage for tryFinalizeMutations where the first multi commits but the caller retries, proving persisted mutation_finish_times values are not changed by the retry.
Final Verdict

Status: ❌ Block

Minimum required actions: fix the csn default regression, make local finish_time writes exception-safe, stop fabricating completion times for legacy local mutation files, and make replicated finish-time persistence idempotent across uncertain Keeper retries.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 19, 2026
- Add `mutation_finish_time` to output expectation of tests that verify replica path children in Keeper
- Fix few code style issues
- `replica_path/mutation_finish_time` breaks upgraded existing replicas that do not have this new
   znode yet. It is fixed by creating the path under Keeper it does not exist and the set operation
   fails on first try. In this case, we create the key and set operation is retried again.
- `check_string_no_advance`might trigger load next chunk on the buffer. In this case, reset the `pos`
   to an old value leaves the buffer in an inconsistent state. This is fixed by reading the remaining
   buffer content into an in-memory read buffer.

   NOTE: In the previous implementation we considered restoring the buffer position as a safe operation
         because the buffer for mutex files is only a few hundred bytes large.
break;

if (!entry.finish_time)
entry.writeFinishTime(time(nullptr));

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.

For legacy local mutation_*.txt entries that do not have finish time, this writes time(nullptr) when the mutation is first observed as done.

That records observation/cleanup time, not real completion time. For pre-feature mutations, completion time is unknown, so emitting a fabricated timestamp is misleading in system.mutations.

Please avoid backfilling legacy entries with "now" and keep finish_time = 0 unless a real completion moment is known.

Since finish time is added as an append operation, it creates
an extra blob on s3.
foadfbf added a commit to foadfbf/ClickHouse that referenced this pull request May 23, 2026
Previously, `mutation_finish_times/*` znodes were removed asynchronously
before the mutation-entry `multi` ran. A failed or retried `multi` could
leave the mutation entry alive with its finish-time znode already gone,
causing `finish_time = 0` after restart for a completed mutation.

Fix: populate `finish_time_removes` only after each mutation-entry `multi`
succeeds (inside the loop, per batch). Removal is then done synchronously
in a `SCOPE_EXIT` via batched `tryMultiNoThrow` calls. `ZNONODE`
(pre-upgrade replicas without the znode) and `ZRUNTIMEINCONSISTENCY`
(sibling ops in a partially-failed multi batch) are silently ignored;
any other error is logged as a warning.

Related PR: ClickHouse#105255

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
foadfbf added a commit to foadfbf/ClickHouse that referenced this pull request May 23, 2026
Using `makeCreateRequest` for `mutation_finish_times/<mutation>` made the
`multi` in `tryFinalizeMutations` non-idempotent: if Keeper committed the
transaction but the client lost the connection before receiving the response,
the next retry would hit `ZNODEEXISTS` on the create op and fail
permanently, blocking `mutation_pointer` from advancing.

Fix: switch to `tryMulti` and on `ZNODEEXISTS` check whether
`mutation_pointer` already matches the expected value. If it does, the
previous `multi` committed and we can safely continue. If it does not, the
error is unexpected and is re-thrown via `KeeperMultiException::check`.

Related PR: ClickHouse#105255

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@foadfbf
foadfbf force-pushed the add-finish-time-system-mutations branch 2 times, most recently from ebfaed9 to fc216d1 Compare May 23, 2026 09:51

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit fc216d1. Configure here.

This change replaces the single `mutation_finish_time` znode with a `mutation_finish_times`
so every mutation in `system.mutations` keeps its own real `finish_time` across restarts instead
of overriding the finish time of previous mutations to the finish time of the last mutation.

In this code path, the in-memory mutation finish time is removed, as it was redundant. Instead,
the code fetches per-mutation finish times alongside the entry data and assigns them to
`MutationStatus.finish_time` at construction.

Accordingly, `tryFinalizeMutations` atomically sets `mutation_pointer` and creates one
`mutation_finish_times/<znode>` child per finished mutation;

For the cleanup, `clearOldMutations` removes the per-replica finish-time children via an
async pipeline guarded by `SCOPE_EXIT`, treating `ZNONODE` as success.
@foadfbf
foadfbf force-pushed the add-finish-time-system-mutations branch from fc216d1 to bf293a3 Compare May 23, 2026 10:27
@nikitamikhaylov nikitamikhaylov self-assigned this Jun 4, 2026

void MergeTreeMutationEntry::writeFinishTime(time_t finish_time_)
{
finish_time = finish_time_;

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.

writeFinishTime sets finish_time before the append, finalize, and sync have succeeded. If any of those operations throws, markFinishedMutationsUnlocked aborts before marking the mutation done, but the in-memory entry now has a non-zero finish_time; the next pass skips the append and can mark the mutation done without ever persisting the timestamp. After a reload, system.mutations.finish_time falls back to 0, which breaks the new persistence contract exactly on the write-failure path.

Please assign finish_time only after the append has been durably completed, or reset it on exception so a later retry will persist the value.

@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.50% +0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.00% 77.10% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 284/286 (99.30%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 33 line(s) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Dear @nikitamikhaylov, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Aug 20, 2026
For non-replicated `MergeTree` tables the completion time is tracked in
memory: `markFinishedMutations` stamps it when a mutation is completed by
an attributable event (the commit of the last mutated part, or the creation
of a mutation that has no parts to process). When the completion moment was
not observed (entries loaded at startup, parts removed by `DROP PARTITION`),
`finish_time` stays zero.

For `ReplicatedMergeTree` tables the completion time is the modification
time of the `mutation_pointer` znode in Keeper, taken from the `set` that
finalizes the mutations on the replica. After the queue state is reloaded
(e.g. on server restart), the finish time of the mutation the pointer points
at is restored from the znode mtime; older completed mutations report zero.

Rework of ClickHouse#105255

Closes ClickHouse#89216

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

Labels

can be tested Allows running workflows for external contributors pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add finish_time to system.mutations

3 participants