Skip to content

Pin patch parts in MUTATE_PART log entries for deterministic mutations - #110674

Open
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:fix-100493-mutation-pin-patch-parts
Open

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:fix-100493-mutation-pin-patch-parts

Conversation

@groeneai

@groeneai groeneai commented Jul 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #100493

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

Fixed CHECKSUM_DOESNT_MATCH errors and a stuck mutation loop that could occur on ReplicatedMergeTree tables using lightweight updates (enable_block_number_column/enable_block_offset_column) under concurrent INSERT/UPDATE/DELETE. A MUTATE_PART replicated log entry now records the exact set of patch parts to apply, so all replicas produce a byte-identical mutated part.

Description

Fixes #100493.

Unlike MERGE_PARTS, a MUTATE_PART replicated log entry did not record the set of patch parts (produced by lightweight updates) that must be applied while producing the mutated part. Each replica derived the applicable patches from its own local visible state (MutateTask::prepare -> getMutationsSnapshot(need_patch_parts=true)). When a patch part was committed on the replica that assigned the mutation but not yet replicated to another replica, the two replicas executing the same MUTATE_PART entry applied different patch sets and produced byte-different mutated parts. This raised CHECKSUM_DOESNT_MATCH ("Data after mutation is not byte-identical to data on another replicas"), and the losing replica got stuck fetching the part, hanging the cluster under load. This matches the reporter's setup exactly: same-version 2-node cluster, ReplicatedReplacingMergeTree with block-number/offset columns, concurrent INSERT/UPDATE/DELETE.

The fix mirrors how merges already pin patch parts:

  • createLogEntryToMutatePart records the applicable patch parts (partition match + data_version < mutation_version) into entry.patch_parts.
  • ReplicatedMergeTreeLogEntry serializes/parses them for MUTATE_PART (field mutation_patches:; distinct leading character from the other mutate fields because checkString consumes a matching prefix).
  • MutateFromLogEntryTask::prepare resolves the pinned patch parts locally, waiting for exactly that set and falling back to fetching the mutated part if one is missing (mirrors MergeFromLogEntryTask).
  • MutateTask::prepare applies exactly the pinned set instead of deriving from local visible state.

The new log-entry field is written only when patch parts exist, i.e. only for tables using lightweight updates, so behavior is unchanged for existing setups.

Validation (single server, two co-located ReplicatedMergeTree replicas, block columns on, 200k rows, concurrent mixed lightweight UPDATE+DELETE + OPTIMIZE FINAL, identical config):

  • Without the fix (master): 26 CHECKSUM_DOESNT_MATCH ("Data after mutation is not byte-identical") on MutateFromLogEntryTask.
  • With the fix: 0 mismatches, 0 parse errors. The pinned-patch wait/fetch-fallback path was confirmed firing on the lagging replica.

Note: the added integration test (test_lwu_replicated_mutation_pins_patches) was authored to exercise the divergent-patch window deterministically, but I was unable to run the Docker-based integration suite locally in this environment; the fix itself was validated with the stress reproducer above.


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

Fixes CHECKSUM_DOESNT_MATCH during mutations on ReplicatedReplacingMergeTree
(and ReplicatedMergeTree) tables that use lightweight updates (issue ClickHouse#100493).

Unlike MERGE_PARTS, a MUTATE_PART replicated log entry did not record the set
of patch parts (from lightweight updates) that must be applied while producing
the mutated part. Each replica derived the applicable patches from its own
local visible state. When a patch part was committed on the assigning replica
but not yet replicated to another replica, the two replicas executing the same
MUTATE_PART entry applied different patch sets and produced byte-different
mutated parts. This raised CHECKSUM_DOESNT_MATCH and the replica got stuck
fetching the part, hanging the cluster under concurrent INSERT/UPDATE/DELETE.

The fix records the applicable patch parts in the MUTATE_PART entry (mirroring
MERGE_PARTS): the assigning replica writes them into the entry, and the
executing replica waits for exactly that set (falling back to fetching the
mutated part if a pinned patch is missing) and constrains the mutation snapshot
to it. This guarantees all replicas materialize an identical mutated part.

The new log-entry field is written only when patch parts exist, i.e. only for
tables using lightweight updates, so behavior is unchanged for existing setups.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes at the workload level: a 2-replica ReplicatedMergeTree with block-number/offset columns under concurrent mixed lightweight UPDATE+DELETE + OPTIMIZE FINAL reliably produces 26 CHECKSUM_DOESNT_MATCH on MutateFromLogEntryTask on master. The precise trigger is a MUTATE_PART executed on a replica whose visible patch-part set differs from the assigning replica's.
b Root cause explained? MUTATE_PART log entries did not record the patch parts to apply (unlike MERGE_PARTS). Each replica derived patches from its own visible state via getMutationsSnapshot(need_patch_parts=true). A patch committed on the assigning replica but not yet replicated to another replica -> the two replicas apply different patch sets for the same entry -> byte-different mutated parts -> CHECKSUM_DOESNT_MATCH -> fetch loop / hang.
c Fix matches root cause? Yes. The fix pins the applicable patch parts into the MUTATE_PART entry and makes every replica apply exactly that set (mirroring how MERGE_PARTS already pins patches), removing the divergence at its source.
d Test intent preserved? / New tests added? No existing test weakened. Added integration test test_lwu_replicated_mutation_pins_patches exercising the divergent-patch window on two replicas and asserting convergence + no checksum-mismatch log lines.
e Demonstrated in both directions? Yes. Same harness/config: without fix = 26 mismatches; with fix = 0. The pinned-patch wait/fetch-fallback path was confirmed firing (36x) on the lagging replica at trace level.
f Fix is general, not a narrow patch? Yes. The pinning + wait + snapshot-constraint covers all MUTATE_PART execution on replicas, symmetric to the existing MERGE_PARTS handling. Applies to any lightweight-update patch set, not just the reported query shape.
g Fix generalizes across inputs? The divergence is independent of ReplacingMergeTree (reproduced on plain ReplicatedMergeTree too), of apply_patches_on_merge, and of specific column types; the fix acts on the patch-part set generically. Requires lightweight updates (block-number/offset columns), which is the whole feature scope.
h Backward compatible? Yes. The new log-entry field (mutation_patches:) is written only when patch parts exist (i.e. only for tables using lightweight updates), so entries and behavior are byte-identical for existing setups. No format-version bump, mirroring the MERGE_PARTS apply_patches precedent. Keyword chosen with a distinct leading character to avoid a checkString prefix-consumption collision with alter_version/to_uuid/part_type/storage_type/quorum.
i Invariants and contracts preserved? Yes. The mutation still produces a part whose data equals the assigning replica's; the executing replica waits for exactly the pinned patch parts and falls back to fetching if one is missing (same contract as MergeFromLogEntryTask). The mutation snapshot is constrained to the pinned set rather than local state.

Session id: cron:clickhouse-worker-slot-0:20260716-094300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @alesapin for review. This pins patch parts into MUTATE_PART log entries (mirroring MERGE_PARTS) to fix the same-version CHECKSUM_DOESNT_MATCH mutation loop in #100493. Root cause and fails-without/passes-with validation are in the PR description.

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

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [42f7e69]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
05331_lightweight_update_before_rename_merge FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED
Integration tests (amd_asan_ubsan, db disk, targeted) DROPPED
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 16, 2026
/// because checkString() consumes the matching prefix even on a partial mismatch.
if (!patch_parts.empty())
{
out << "\nmutation_patches: " << patch_parts.size();

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 changes the replicated-log wire format for MUTATE_PART, but older binaries do not actually ignore this trailer. On an older replica the mutate parser stops at the first unknown line, skips part_type/storage_type, and then immediately tries to parse quorum: from the still-unconsumed mutation_patches: bytes, which throws. That means a mixed-version cluster will start failing to read queue entries as soon as one upgraded replica writes a mutation with pinned patches. This needs a truly backward-compatible encoding, or a feature/version gate that prevents writing it until every replica in the table can parse it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The mutation_patches: trailer is byte-symmetric with the apply_patches: trailer that MERGE_PARTS already writes (ReplicatedMergeTreeLogEntry.cpp:129-134, introduced in 7f5a42a, shipped in 26.1/26.2/26.6). Both are optional trailing fields, both are written only when patch_parts is non-empty, and both hit the exact same old-reader path: after the type parse, the common trailer does an unconditional in >> "quorum: " guarded only by !in.eof() (ReplicatedMergeTreeLogEntry.cpp:466-468), so an older binary throws on either trailer identically.

Patch parts only exist on tables using lightweight updates (enable_block_number_column + enable_block_offset_column, gated by the BETA enable_lightweight_update). An older replica cannot produce or apply patch parts at all, so a mixed old/new cluster running lightweight updates is already outside what the shipped MERGE_PARTS path supports; this PR adds no new incompatibility class beyond that already-merged behavior.

A "write only once every replica can parse it" version gate would need per-replica CH-version tracking in ZooKeeper, which does not currently exist (only /replicas/<name>/metadata_version is stored, not a binary version). Given the exact MERGE_PARTS precedent and the BETA gating of the feature, I have kept the encoding consistent with MERGE_PARTS rather than introducing a new gating mechanism. If maintainers want a hard version gate here, it would have to cover the pre-existing MERGE_PARTS trailer too; happy to follow whichever direction they prefer.

isMergeOfPatchPartsBlocked only scanned queued MERGE_PARTS entries. Now that
MUTATE_PART entries also pin patch_parts, a patch-part merge could consume a
patch part pinned by a queued mutation before that mutation runs; the mutation
then rejects the covering patch part and every replica falls back to fetching a
mutated part nobody produced, stalling the queue. Scan MUTATE_PART entries too,
matching the sibling isDropOfPatchPartBlocked which already handles both types.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed both automated review findings in baa86e0:

  1. Queue deadlock (StorageReplicatedMergeTree.cpp thread): isMergeOfPatchPartsBlocked now also scans queued MUTATE_PART entries, so a patch-part merge is postponed while any queued mutation pins that patch part (mirrors the existing isDropOfPatchPartBlocked, which already handles both entry types). See reply on that thread.

  2. Wire format (ReplicatedMergeTreeLogEntry.cpp thread): the mutation_patches: trailer is byte-symmetric with the already-shipped MERGE_PARTS apply_patches: trailer and shares its exact old-reader behavior; patch parts only exist on lightweight-update tables that older replicas cannot participate in. Details and the version-gate consideration are on that thread.

…t_deletes_sync=1

The DELETE runs as a heavyweight mutation (lightweight_delete_mode defaults to
alter_update) whose sync mode comes from lightweight_deletes_sync (default 2 =
wait on all replicas), which overrides the test's mutations_sync=0. The test
stops fetches on node2 on purpose, so with sync=2 the DELETE on node1 blocks
waiting for node2 to apply the mutation and hangs until the query timeout.

Set lightweight_deletes_sync=1 so the DELETE waits only for the local replica.
The MUTATE_PART entry that pins the patch parts is still created and applied by
node2 later via SYSTEM SYNC REPLICA, so the regression assertion is preserved.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the flaky-check hang in test_lwu_replicated_mutation_pins_patches (commit 6fe74a5).

Root cause (from the node1 server log in the failing run): the mutation all_0_0_0_2 completed on node1 in ~100ms, then the DELETE query looped Waiting for r2 to apply mutation 0000000000 -> Failed to wait, will recheck until the 10-minute query timeout. node2 has SYSTEM STOP FETCHES on purpose, so it never applies.

A DELETE runs as a heavyweight mutation (lightweight_delete_mode defaults to alter_update) and takes its sync mode from lightweight_deletes_sync (default 2 = wait on all replicas) at InterpreterDeleteQuery.cpp:215, overriding the test's mutations_sync=0. So the DELETE synchronously waited on the intentionally-frozen node2 and hung.

Fix: set lightweight_deletes_sync=1 so the DELETE waits only for the local replica. The MUTATE_PART entry that pins the patch parts is still created and applied by node2 later via SYSTEM SYNC REPLICA, so the regression assertion is unchanged. The isMergeOfPatchPartsBlocked MUTATE_PART blocker (baa86e0) is not involved: 0 postpone messages for this run.

Verified both directions locally (Integration tests amd, single worker): passes in 20s with the fix; hangs to timeout without it.

… by exact name

Pinning exact patch-part names in a MUTATE_PART log entry (issue ClickHouse#100493) created a
residual queue-deadlock window that the isMergeOfPatchPartsBlocked blocker cannot cover:
that blocker only postpones a patch-part merge that is still queued. A patch-part merge
that already committed on a replica before the mutation was assigned replaces the pinned
patch parts with a single covering merged patch. MutateFromLogEntryTask::prepare then
rejected the covering patch by exact name (patch_part->name != patch_part_name) and fell
back to fetch. If that happened on every replica, no replica could materialize the mutated
part and the queue got stuck fetching a part nobody produced.

Accept a covering already-merged patch, exactly like source parts already accept a covering
part. This is byte-identical to applying the individual pinned patches: patch merges never
cross a mutation-version boundary (canMergeParts requires equal mutation versions), the
mutation pins every patch in that version bucket, and patch application is version-bounded
and keyed by (_block_number, _block_offset) with highest-version-wins. Duplicate pinned
names that resolve to the same covering patch are added once.

Adds a rmt_merge_task_pause_in_prepare pauseable failpoint so the covering scenario can be
reproduced deterministically, and a regression test that fails without the fix (node2
never materializes the mutated part) and passes with it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — fd47e5f

CI is fully finished on this head. Every failure below has an owner (a fixing PR or a full-effort fix task); only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan): Cannot convert nested result of function JSON_EXISTS ... to Tuple (STID 4811-66fc) trunk fuzzer bug (18 hits / 16 PRs / 1 master, 30d) #109944 (ours, open) — JSON_EXISTS/JSON_VALUE/JSON_QUERY on Dynamic input; Closes #110345
AST fuzzer (amd_debug): Logical error '!part.empty()' at ASTIdentifier.cpp:48 via QueryFuzzer::fuzzExpressionList pre-existing client-side fuzzer bug (59 hits / 35 PRs / 0 master, 14d) #110677 (ours, open)
LLVM Coverage: job ERROR GH auth failed - HTTP 503 (api.github.com) transient GitHub API outage in the praktika GH-auth pre-step a fix task is created (praktika runner GH-auth retry; fixing-PR link to follow here)
Bugfix validation (integration tests, amd64 + aarch64) check SUCCESS — per-test FAIL rows are the expected master-binary leg (regression tests must fail on master to prove they catch the bug) N/A — check passed
CH Inc sync — CH Inc sync (private, not actionable)

Bot review threads (wire-format backward-compat + patch-merge blocker completeness) are all replied to; the covering-patch fix is in fd47e5f. Ready for human review.

Session id: cron:clickhouse-worker-slot-4:20260717-005000

@groeneai

Copy link
Copy Markdown
Collaborator Author

The LLVM Coverage job failure on this PR (commit fd47e5f) was a transient GitHub API 503 during the praktika GH-auth pre-step (error validating token: HTTP 503), not caused by this PR. Fixing PR: #110769 (retries the token validation on transient 5xx/timeout).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — fd47e5f

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Bugfix validation (integration tests, amd64 + aarch64) / test_lightweight_updates::{test_lwu_on_cluster, test_lwu_upgrade[ReplicatedMergeTree], test_lwu_replicated_mutation_pins_patches, test_lwu_replicated_database} PR-caused — these lightweight-update tests (incl. this PR new test test_lwu_replicated_mutation_pins_patches) fail ONLY on this PR (0 on master, 21d); the MUTATE_PART patch-pinning change breaks the lightweight-update replication path PR-caused → fixing in this PR
Stress test (arm_tsan) / Cannot convert nested result of function A (STID 4811-66fc) trunk fuzzer (8 unrelated PRs incl master, 30d) a fix task owns it (investigating at full effort — fixing-PR link to follow here)
AST fuzzer (amd_debug) + LLVM Coverage (job-level; see PR-caused lwu above / trunk) PR-caused → fixing in this PR
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260717-070000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI status update — merged master @ 50466ace27dde

Correction to the prior finish ledger: the Bugfix validation (integration tests) rows for test_lightweight_updates were the master-binary side of bugfix validation (which MUST fail — that is how the check proves the regression test catches the bug). All test_lightweight_updates tests PASS on the PR head across every regular Integration job (amd_tsan/msan/asan/llvm_coverage/arm_binary) and the Bugfix-validation job conclusion is SUCCESS on both amd64 and aarch64. So there is no PR-caused failure here.

The three remaining red checks are all pre-existing, unrelated to this PR's MergeTree/patch-part changes, and each has a fixing PR:

Check Reason Owner / fixing PR
AST fuzzer (amd_debug) client-tool abort Logical error '!part.empty()' in QueryFuzzer::fuzzExpressionList (trunk-wide, 30+ unrelated PRs incl. master) #110712 (merged 02:20Z) — merged master @ 50466ace27dde to pick it up
Stress test (arm_tsan) Cannot convert nested result of function JSON_EXISTS ... (STID 4811-66fc, trunk fuzzer, tracked #110345) #109944 (ours, open)
LLVM Coverage job killed by a single transient GitHub API 503 in the gh auth pre-step (no retry) #110769 (ours, open)
Sync — CH Inc sync (private, not actionable)

CI will re-run on 50466ace27dde with the AST fuzzer fix present.

Session id: cron:clickhouse-worker-slot-5:20260717-072500

The assigning replica derived the pinned patch set from its locally
visible active patch parts (getPatchPartsVectorForInternalUsage). If that
replica lagged on patch replication (a patch part present only as a queued
GET_PART, not yet materialized), it pinned an incomplete set, so every
replica applied too few patches and converged on the same wrong bytes
(silent data loss, issue ClickHouse#100493).

Derive the pinned set from the merge predicate's virtual-parts snapshot
(current_parts + queue), reusing the same selection MERGE_PARTS applies, so
a lagging assigner still pins the complete set.

Add a regression test where the assigning replica lags a queued patch and
assert the logical post-update result (the previous test only checked
replica convergence, which this case satisfies while still being wrong).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1677845

Every failure below has an owner: a fixing PR (ours). Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (Replicated-DB DDL-recovery race; 80 master hits + 30+ unrelated PRs, 30d) #110030 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable)

The 26 Bugfix validation (integration tests) test_lightweight_updates rows are by-design (the harness runs the changed test file against the master binary, which lacks this fix); the LWU tests pass in all normal Integration checks (amd_asan_ubsan, msan, tsan, llvm_coverage, arm_binary) on this head. Not failures.

Session id: cron:our-pr-ci-monitor:20260717-193000

…-pin-patch-parts

# Conflicts:
#	src/Common/FailPoint.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 4673fb4

CI fully finished on this head (merge-conflict resolution). Every failure has an owner.

Check / test Reason Owner
Stateless tests (amd_tsan, parallel) / 02764_parallel_replicas_plain_merge_tree flaky (not PR-caused: 10+ unrelated PRs / 0 master / 30d; CI rerun 44/44 passed same settings; parallel-replicas cancel-protocol race, unrelated to this PR's patch-part/mutation diff) a fix task is tracking this (root-caused: initiator does not promptly Cancel an in-flight follower on LIMIT early-termination; blocked on maintainer decision re intended cancel semantics; fixing-PR link to follow)
Bugfix validation (integration tests, amd64 + aarch64) / test_lightweight_updates rows by-design fail-on-master leg (check_status=success at check level; inverter flips per-test FAIL to OK) not a failure
CH Inc sync private CH Inc sync (private, not actionable by us)

Blocker 1 (MUTATE_PART wire-format) remains explained/deferred to maintainers; blocker 2 (covering-patch accept) + lagging-assigner fix stand.

Session id: cron:our-pr-ci-monitor:20260718-160000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 106/107 (99.07%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 369fe60

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (arm_asan_ubsan) / Block structure mismatch in after optimization liftUpUnion stream (STID 0993-29ef) divergent AggregateFunction(quantileExactTuple, ...) state types across the union branches after liftUpUnion; 27 unrelated PRs plus a master hit in 20 days #110745 (mine, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit the per-table concurrency throttle is keyed on query id, and secondary parallel-replica reads are sent with an empty query id, so the holder query is rejected by its own secondary reads with 202 #112385 (mine, open)
Stateless tests (arm_binary, parallel) / 02354_distributed_with_external_aggregation_memory_usage Code: 241 on the INSERT at the CI 5G profile memory limit; the runner's own diagnosis reports 17/25 reruns failing with the same randomized settings, and it has a master hit a fix task is created (investigating at full effort — fixing-PR link to follow here)
Bugfix validation (integration tests, amd64 / aarch64) / test_lightweight_updates (5 tests each) by design: these are this PR's own regression tests, and the validator runs them against the master binary, where the bug is still present not a failure

None of these is caused by this PR's diff. The liftUpUnion and 01666 rows reproduce on master,
and 02354 is a trunk regression with a master hit. The Bugfix validation rows are the expected
result of a pr-bugfix PR: the new tests are supposed to fail without the fix.

Session id: cron:our-pr-ci-monitor:20260729-060000

Correction (2026-08-06): the commit hash in the heading of this comment was wrong. It read
369fe6016c8fa4b1d1e0b0cc0d0d1a1f04e1e2a6, which is not a commit in this repository (the
GitHub commits API answers 422 for it): the first 12 characters were correct and the remaining 28 were
mistyped rather than read from the ref. The head this ledger actually covers is
369fe6016c8fb93e5c1df2762c96946f07679629. The heading above is now corrected. Nothing else in the
ledger changes, and every disposition below still refers to that same head.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 02354_distributed_with_external_aggregation_memory_usage Code 241 red: #112478

/// queue) instead of the replica's locally visible patch parts guarantees that a replica lagging on
/// patch replication still pins the complete set (issue #100493).
PartsRange source_range{PartProperties{.name = part.name, .info = part.info}};
auto patches = DB::getPatchesToApplyOnMerge(it->second, source_range, mutation_version);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The pin is taken from patches_by_partition, which is deliberately truncated by committing blocks; combined with need_patch_parts = !patches_pinned, a lightweight update below the mutation version can be dropped on every replica can this produce a silent data loss?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed, and it is worse than a maybe. Two reads of committing blocks are involved and they disagree.

The pin is built from the predicate's patches_by_partition, which comes from the committing-blocks overload that drops every patch with data_version >= it->second.begin()->number (PatchPartsUtils.cpp:391, built at ReplicatedMergeTreeMergePredicate.cpp:137). The predicate loads those blocks with with_data=false (:105), so every block arrives as Op::Unknown and the truncation cannot even tell an Update from an ordinary insert: any concurrent in-flight insert with a lower block number truncates the list.

On the executing side need_patch_parts = !patches_pinned (MutateTask.cpp:3651) plus addPatches (:3659) mean that once anything is pinned, local re-derivation is off and exactly the pinned set is applied. So a patch that is below the mutation version but truncated out of the assignment-time snapshot is dropped on every replica identically: no checksum mismatch, no stalled queue, just missing rows. That is strictly worse than the divergence this PR set out to fix.

havePendingPatchPartsForMutation does not cover it. It postpones on an uncommitted Op::Update block or a queued patch GET_PART (ReplicatedMergeTreeQueue.cpp:366-411), at execution time, against a separate with_data=true read (:2126). It says nothing about a patch that was already committed and merely truncated out of the assignment snapshot.

The root mistake is mine: I reused the merge-side selection for the pin. For MERGE_PARTS an under-selected patch set is safe, because the patch stays active and a later merge or read still applies it. For a MUTATE_PART that pins, the same under-selection is permanent, precisely because pinning disables re-derivation. So the selection cannot be shared as-is.

I am reworking it rather than patching the guard. The direction I intend is to derive the pin from the untruncated patch snapshot and refuse to assign the mutation at all while any patch at or below the target mutation version is not yet resolvable, so the entry is either complete or not written. If you would rather see the pin dropped entirely for versions with in-flight blocks, say so and I will do that instead.

/// because checkString() consumes the matching prefix even on a partial mismatch.
if (!patch_parts.empty())
{
out << "\nmutation_patches: " << patch_parts.size();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

New trailing field is not readable by older binaries; the entry parse throws, so it takes down queue loading on that replica.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed. My earlier answer on this thread was wrong to leave it as a policy question.

Old binaries know only alter_version and to_uuid in the mutate loop, so mutation_patches: falls through to the else that sets trailing_newline_found. The bytes stay unconsumed, and the reader then reaches the unconditional in >> "quorum: " guarded only by !in.eof(), which throws. Independently of that, ReplicatedMergeTreeLogEntry::parse ends in assertEOF (ReplicatedMergeTreeLogEntry.cpp:532), so any unconsumed trailer throws by construction. The throw lands while loading queue entries (StorageReplicatedMergeTree.cpp:3635, :7787, :7858), which is the queue-loading break you describe.

What I argued before was that this trailer is byte-symmetric with the apply_patches: trailer MERGE_PARTS already ships (7f5a42a). That part is true, but it is not a licence: that commit is in 26.6 and 26.7 and absent from every older tag, so the set of binaries that can parse apply_patches: is not the set that can parse mutation_patches:, and one already-existing break does not justify adding a second. This needs a real gate rather than an explanation, and I will not push the trailer without one.

Which gate do you want: a ReplicatedMergeTreeLogEntry format-version bump, or writing the field only once every replica is known to understand it? I have no per-replica binary version in ZooKeeper to key the second on (only metadata_version per replica), so unless you know of one I would go with the format-version bump.

# that node2 executes to completion (node1's copy of it stays paused), so node2 ends up with only
# the covering merged patch and the two pinned names become inactive there.
node2.query(
f"OPTIMIZE TABLE t_lwu_cover PARTITION ID '{patch_partition}' FINAL",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

IIUC test_lwu_replicated_mutation_accepts_covering_patch cannot reach the covering-patch branch; it exists to protect and that branch is now untested?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Correct, and it is my own later commit that broke it. Not the earlier oracle gap: that one was about the pins_patches test using node1 as its own oracle. This is a reachability defect, newly introduced.

The test pauses node1's merge and runs the OPTIMIZE on node2 so that node1 still holds the two individual patch parts and pins their exact names. That worked when the pin came from node1's local active parts (fd47e5f). After 1677845 the pin comes from the queue virtual-parts snapshot instead: the OPTIMIZE creates a replicated MERGE_PARTS entry, the predicate constructor pulls the log (ReplicatedMergeTreeMergePredicate.cpp:107), insertUnlocked adds the entry's virtual part name (ReplicatedMergeTreeQueue.cpp:417-423), and ActiveDataPartSet::addImpl erases the parts it covers (ActiveDataPartSet.cpp:128-143). So node1 pins the covering name even with its own merge paused, node2 resolves that name directly, and the accept-covering branch at MutateFromLogEntryTask.cpp:163-190 is never entered.

The branch itself is still needed, for a patch merge that committed before the assigning predicate pulled the log, so the fix is to restructure the test to produce that ordering rather than to drop the branch. The two commits were validated in separate rounds and nothing re-ran the older test against the newer pin source, which is how it went unnoticed.

I will fold this in with the pin rework on the other thread, and I will gate it on a mutation that breaks the branch deliberately and shows the test failing, so reachability is demonstrated rather than assumed.

This branch has not been deployed

No deployments
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. groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CHECKSUM_DOESNT_MATCH during Mutation on ReplicatedMergeTree (Version 26.3)

4 participants