Skip to content

Fix data loss when replicated INSERT commit recovery is interrupted - #111196

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
kakao-tars-case:fix-replicated-insert-ambiguous-commit-rollback
Sep 12, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
kakao-tars-case:fix-replicated-insert-ambiguous-commit-rollback

Conversation

@kakao-tars-case

@kakao-tars-case kakao-tars-case commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Related: #56917
Related: #47985
Related: #106424

When the Keeper multi request committing an INSERT into ReplicatedMergeTree succeeds but its response is lost, ClickHouse verifies the uncertain commit with retried exists requests. Previously, if this recovery loop exited through max_execution_time, KILL QUERY, or another non-retryable exception, actionAfterLastFailedRetry was bypassed and the local part was rolled back. Keeper could already contain the part metadata, replication log entry, and deduplication block ID, so a repeated INSERT was deduplicated while the committed data remained unavailable.

Any exception leaving the recovery loop is now treated as an unknown commit status. The local part is preserved when it is still owned by the transaction, enqueued for a part check, and the recovery path raises UNKNOWN_STATUS_OF_INSERT. The part is rolled back and retried only after Keeper explicitly confirms that it was not committed.

If the query has already been cancelled, PipelineExecutor may report the original TIMEOUT_EXCEEDED or QUERY_WAS_CANCELLED error instead of the sink's UNKNOWN_STATUS_OF_INSERT. The local part is preserved in either case, and these client-visible errors still represent an unknown insertion status.

For writeExistingPart paths used by ATTACH PART and RESTORE, the preserved part is marked as owned by the working set only after its local commit succeeds; the same ordering is applied to the two success paths of commitPart. The exception handler therefore keeps an already committed part in the table data path, while a part whose local commit failed is still renamed back to detached/ or tmp_restore_*, where its data is preserved.

Added deterministic integration coverage for recovery interrupted by both max_execution_time and KILL QUERY. The tests verify that the local data remains readable, a repeated INSERT is deduplicated, and lost_part_count does not increase.

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed potential data loss when an INSERT into ReplicatedMergeTree was cancelled or timed out while ClickHouse was recovering an uncertain Keeper commit.


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

Version info

  • Merged into: 26.9.1.1229 (included in 26.9 and later)
  • Backported to: 26.8.3.98, 26.7.7.87, 26.6.5.114, 26.3.33.61

…ncelled while the Keeper commit status is unknown

When the Keeper multi request committing an INSERT ends with a hardware
error (e.g. connection loss), the request may or may not have been
applied, so `ReplicatedMergeTreeSinkImpl::commitPart` verifies the status
with an `exists` check under `ZooKeeperRetriesControl`. The preservation
logic previously lived in the `actionAfterLastFailedRetry` callback,
which only runs when the retries are exhausted by Keeper errors: a
`max_execution_time` timeout, `KILL QUERY` or any non-retryable exception
thrown during the recovery bypassed it, the exception left `commitPart`
and `MergeTreeData::Transaction` rolled back the local part. Keeper,
however, could already contain the part metadata, the replication log
entry and the deduplication block id, so the part became lost forever
(replaced by an empty part by the part check), and retrying the same
INSERT was silently deduplicated - permanent data loss. The regression
exists since 23.12: the verify-first recovery introduced by ClickHouse#56917
interacts with the time limit checks between retries introduced by

Now the recovery result is explicit: unless the recovery loop completes
the Keeper checks and produces a result, the commit status is treated as
unknown on any exit path, and the local part is preserved - committed
locally and enqueued for a part check, which keeps it if it is present
in Keeper or drops it otherwise. `actionAfterLastFailedRetry` is
deliberately not used: its contract does not cover cancellation or
non-retryable failures. On these paths the INSERT now fails with
`UNKNOWN_STATUS_OF_INSERT` instead of `TIMEOUT_EXCEEDED` /
`QUERY_WAS_CANCELLED`, consistently with the exhausted-retries path,
so that clients do not interpret the failure as "the data was not
inserted".

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

CLAassistant commented Jul 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@thevar1able thevar1able added the can be tested Allows running workflows for external contributors label Jul 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3c433f6]

Summary: ✅


AI Review

Summary

This PR fixes the main data-loss bug around interrupted ambiguous Keeper commit recovery in ReplicatedMergeTree, and it also closes the earlier ATTACH PART / RESTORE rollback gaps with focused integration coverage. I found one remaining follow-up in the new cleanup path for quorum inserts: when failed-quorum cleanup has already detached the part, the new delayed part check is still enqueued and can turn into a permanent background recheck loop.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp:1075] The new "unknown status" path enqueues a delayed part check even after removeFailedQuorumParts() has already detached the part and removed its virtual-part coverage. In that state the checker sees "not in Keeper, not local" and, on the common case where no replica has the part anymore, keeps re-enqueuing the same name every 30 seconds instead of converging. Suggested fix: only call enqueuePartForCheck() when the branch actually preserved the part locally (part->getState() == PreActive and transaction.commit(parts_lock) succeeded); skip it after the failed-quorum cleanup branch that calls transaction.clear().
Tests

⚠️ Add a quorum regression where the Keeper multi result is ambiguous, recovery is interrupted, and removeFailedQuorumParts() detaches the part before this branch finishes. The test should assert that no stale part-check retries remain for that part (and that lost_part_count stays unchanged).

Final Verdict

Changes requested.

LLVM Coverage Report

⚠️ No coverage measurement for commit 3c433f6: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_6.profdata.

@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 Jul 21, 2026
kakao-tars-case and others added 2 commits July 22, 2026 13:30
…unknown

`writeExistingPart` (used by `ATTACH PART` and `RESTORE`) rolls back the
on-disk rename of the part on any exception from `commitPart` unless
`new_part_was_committed_to_zookeeper_after_rename_on_disk` is set. The
preserve path commits the part into the working set and throws
`UNKNOWN_STATUS_OF_INSERT`, but did not set the flag, so
`try_rollback_part_rename` renamed the already-committed part back to
`detached/` or `tmp_restore_*`, leaving an active part whose directory
is outside the table data path. Set the flag before committing, in the
same way as the successful recovery path does.

Co-Authored-By: Claude Fable 5 <[email protected]>
When the recovery of an ambiguous Keeper commit is aborted by a query
timeout or `KILL QUERY`, the pipeline executor cancels the query before
the exception-carrying chunk of the sink reaches the end of the
pipeline, so the sink's `UNKNOWN_STATUS_OF_INSERT` is dropped and the
client receives the original `TIMEOUT_EXCEEDED` / `QUERY_WAS_CANCELLED`
error. Assert these codes instead of `UNKNOWN_STATUS_OF_INSERT`. The
invariants that actually guard the fix - the part stays readable, the
retried `INSERT` is deduplicated, `lost_part_count` stays 0 - are
asserted separately.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111196&sha=5b6739251333d0d68bc3be36ff66860f9ee19ac9&name_0=PR
PR: ClickHouse#111196

Co-Authored-By: Claude Fable 5 <[email protected]>
The test used an unstable , for which ClickHouse disables deduplication. As a result, retrying the insert correctly created another part and made the row-count assertion fail. Add  to the original and retried inserts so they generate the same deduplication block ID and exercise the intended ambiguous Keeper commit path.
Set `new_part_was_committed_to_zookeeper_after_rename_on_disk` only after the local `MergeTreeData::Transaction::commit` succeeds in the ambiguous Keeper recovery path. This keeps the existing `writeExistingPart` rename rollback when the local commit itself fails while still protecting a successfully preserved part from the terminal unknown-status exception.
kakao-tars-case and others added 2 commits July 22, 2026 17:02
Apply the same ordering as in the ambiguous-commit preserve path to the
two success paths of `commitPart`: set
`new_part_was_committed_to_zookeeper_after_rename_on_disk` only after
`transaction.commit` succeeds. If the local commit throws before the
part becomes visible in the working set, `writeExistingPart` can still
rename the part back to `detached/` or `tmp_restore_*`, where the data
is preserved instead of being deleted by the cleanup thread.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

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

Full report · Diff report

@kakao-tars-case

Copy link
Copy Markdown
Contributor Author

All four failed CI jobs look unrelated to this PR: known flaky tests (#111067, #111289, #110036), and test_cancel_backup passed on retry.

@clickhouse-gh clickhouse-gh Bot added the comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. label Sep 4, 2026
@CheSema CheSema self-assigned this Sep 7, 2026
@CheSema

CheSema commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

You found and fixed a real complex bug, thank you.
Tests reproduce the issue and code addresses it correctly.

My thoughts about actionAfterLastFailedRetry.
After that PR this method would be used only in the one place in resolveQuorum. I suspect that there we have the same issue. Might be it is not so severe but still.
I also could assume that the bug was made here due to false assumption about how actionAfterLastFailedRetry works.
So, the question, what we need to do with resolveQuorum?
Options:

  • remove it and handle it carefully at the site
  • make it reliable by either:
    • call it after the all exceptions, not only after keepers exceptions
    • stop trowing from the loop predicate canTry

I lead to the first option: in the following PR remove the last usage of actionAfterLastFailedRetry and remove it self. If we need similar function again we will implement it with more care next time.

…lback

Refresh the branch on top of current `master` to re-run CI. The branch was
25707 commits behind. The merge is clean; the change to
`ReplicatedMergeTreeSink.cpp` and the integration tests are unchanged.
@@ -1061,24 +1073,37 @@ std::vector<DeduplicationHash> ReplicatedMergeTreeSink::commitPart(
}
}
storage.enqueuePartForCheck(part->name, MAX_AGE_OF_LOCAL_PART_THAT_WASNT_ADDED_TO_ZOOKEEPER);

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 part->getState() != MergeTreeDataPartState::PreActive, this branch already knows that removeFailedQuorumParts() won the race and detached the part (ReplicatedMergeTreeRestartingThread.cpp:295-296). Enqueuing the original part name for a delayed check is then the wrong cleanup contract: five minutes later ReplicatedMergeTreePartCheckThread will see "not in Keeper, not local", and on the common failed-quorum case where no replica has the part anymore it falls into TryFetchMissing and keeps re-enqueuing the same name every 30 seconds because createEmptyPartInsteadOfLost() refuses parts that are no longer covered by virtual_parts (ReplicatedMergeTreePartCheckThread.cpp:525-542, StorageReplicatedMergeTree.cpp:11649-11654).

So a quorum insert whose ambiguous commit recovery is interrupted can leave a permanent part-check loop/log spam after the failed-quorum cleanup already decided to discard the part. Please only call enqueuePartForCheck() when this branch actually preserved the part locally (the PreActive branch), and skip it when the cleanup path already detached it.

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3c433f613 with master 58f74d473 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d9a179ec7; 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

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

Job report

@kakao-tars-case

Copy link
Copy Markdown
Contributor Author

You found and fixed a real complex bug, thank you. Tests reproduce the issue and code addresses it correctly.

My thoughts about actionAfterLastFailedRetry. After that PR this method would be used only in the one place in resolveQuorum. I suspect that there we have the same issue. Might be it is not so severe but still. I also could assume that the bug was made here due to false assumption about how actionAfterLastFailedRetry works. So, the question, what we need to do with resolveQuorum? Options:

  • remove it and handle it carefully at the site

  • make it reliable by either:

    • call it after the all exceptions, not only after keepers exceptions
    • stop trowing from the loop predicate canTry

I lead to the first option: in the following PR remove the last usage of actionAfterLastFailedRetry and remove it self. If we need similar function again we will implement it with more care next time.

Thanks for the review!
It looks like the same callback issue can occur in resolveQuorum, though the impact seems less severe there since the part has already been committed locally.
I agree that handling it explicitly in resolveQuorum and removing actionAfterLastFailedRetry makes sense.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit f039c23 Sep 12, 2026
175 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 12, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 12, 2026
Backport #111196 to 26.8: Fix data loss when replicated INSERT commit recovery is interrupted
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 12, 2026
Backport #111196 to 26.7: Fix data loss when replicated INSERT commit recovery is interrupted
robot-clickhouse-ci-2 added a commit that referenced this pull request Sep 12, 2026
Cherry pick #111196 to 26.6: Fix data loss when replicated INSERT commit recovery is interrupted
robot-clickhouse added a commit that referenced this pull request Sep 12, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Sep 12, 2026
Cherry pick #111196 to 26.3: Fix data loss when replicated INSERT commit recovery is interrupted
robot-clickhouse added a commit that referenced this pull request Sep 12, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 12, 2026
Backport #111196 to 26.6: Fix data loss when replicated INSERT commit recovery is interrupted
alexey-milovidov added a commit that referenced this pull request Sep 12, 2026
Backport #111196 to 26.3: Fix data loss when replicated INSERT commit recovery is interrupted
feiyunwill pushed a commit to feiyunwill/ClickHouse that referenced this pull request Oct 5, 2026
…hronously

Since ClickHouse#111663 a single-block INSERT ... SELECT into MergeTree takes the
async insert queue by default. The client query then only waits for the
flush, while the sink and its Keeper retry loop run in the flush under
another query id, so KILL QUERY and max_execution_time stop only the wait.

test_ambiguous_zk_commit_kill_preserves_data failed on master
(Integration tests (arm_binary, distributed plan, 3/4)) because its
count() raced the flush's next retry: the part landed 70 ms after the
read. The kill test also no longer reached the ambiguous-commit preserve
path of ClickHouse#111196, the timeout test's TIMEOUT_EXCEEDED came from the wait,
and the < 10 s bound of test_query_timeout_with_zk_down was met by the
wait while the flush kept retrying.

Pin async_insert=0 on these three inserts and on the two deduplication
re-inserts, which model a client retrying the same statement, as ClickHouse#111663
did for test_jbod_balancer, test_azure_403_handling and
test_rename_column.

Co-Authored-By: Claude Opus 5.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 comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants