Skip to content

Fix LOGICAL_ERROR and data loss in mutation when part.metadata_version > table.metadata_version - #102349

Closed
tiandiwonder wants to merge 1 commit into
ClickHouse:masterfrom
tiandiwonder:fix-mutation-part-metadata-version-mismatch
Closed

tiandiwonder wants to merge 1 commit into
ClickHouse:masterfrom
tiandiwonder:fix-mutation-part-metadata-version-mismatch

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor
When a ReplicatedMergeTree replica fetches a part from a more advanced replica
(part.metadata_version > table.metadata_version), a subsequent mutation on that
part could either throw LOGICAL_ERROR in splitAndModifyMutationCommands, or
silently discard the extra columns (data loss).

Root cause: splitAndModifyMutationCommands handled part_version < table_version
(column was DROPped) but not part_version > table_version (column comes from a
future schema not yet applied locally).

Fix: pass through extra columns from the more advanced part into the mutation
output unchanged. Build an effective_metadata_snapshot that extends the table
schema with the passthrough columns and sets metadata_version to
max(table_version, part_version). Pass this snapshot to MutationsInterpreter
and MergedBlockOutputStream so that codec lookup, column resolution, and the
final metadata_version.txt all use the correct values.

In finalizeMutatedPart (wide-part subset path), write new_data_part->getMetadataVersion()
instead of metadata_snapshot->getMetadataVersion() so the part carries the
correct version after the mutation.

Tests:
- 04092: single-replica deterministic test — file-system manipulation sets
  part.metadata_version to MV+2, DROP COLUMN h advances table to MV+1, KILL
  MUTATION leaves the mismatch in place, then UPDATE b=1 must complete without
  exception. Verifies column h is preserved in the output part, metadata_version
  equals ADVANCED_MV, and re-adding h with a distinct default does not trigger
  materialisation (original val_N values survive).
- 04093: two-replica replication integrity test — FETCH PART transfers
  metadata_version.txt (modern protocol), ATTACH creates the part.meta > table.meta
  state, mutation completes after schema catches up, and h values (rep_N) are
  preserved intact. Includes both existence (countDistinct(a)=50) and value-
  correctness (WRONG=0) assertions.

Fixes #102153

Prior Fix and Revert

┌────────┬─────────────────────────────────────────────────────────────────────────────┬─────────────┐
│   PR   │                                 Description                                 │   Outcome   │
├────────┼─────────────────────────────────────────────────────────────────────────────┼─────────────┤
│ #96008 │ For part > table: log warning and fall through to                           │ Merged      │
│        │ for_interpreter.emplace_back(READ_COLUMN h)                                 │             │
├────────┼─────────────────────────────────────────────────────────────────────────────┼─────────────┤
│ #97301 │ Reverted by alesapin with reason: "replaces LOGICAL_ERROR with potential    │ Revert      │
│        │ data loss"                                                                  │ merged      │
└────────┴─────────────────────────────────────────────────────────────────────────────┴─────────────┘

Analysis of why the revert was justified:

PR #96008 caused column h to enter for_interpreter as a READ_COLUMN command, so MutationsInterpreter
would attempt to SELECT column h. However, available_columns — derived from
metadata_snapshot->getColumns().getNamesOfPhysical() — does not include h, causing the interpreter to
throw UNKNOWN_IDENTIFIER: Missing columns: 'h' at execution time. Even setting that error aside, the
output part's metadata_version would be written as the current table version (N), while the part
physically contains column h. This leaves the part in an inconsistent state: on the next mutation,
part.meta == table.meta but h is present in the part yet absent from the schema, which is a genuine
invariant violation.

Changelog category (leave one):

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

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

Fix mutation LOGICAL_ERROR and silent data loss when a part fetched from a more advanced replica has
part.metadata_version > table.metadata_version

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@clickhouse-gh

clickhouse-gh Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [53be33e]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) failure
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
Stateless tests (amd_tsan, flaky check) failure
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
Stateless tests (amd_msan, flaky check) failure
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
Scraping system tables FAIL cidb
Stateless tests (amd_debug, flaky check) failure
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
Stateless tests (amd_binary, flaky check) failure
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) failure
04078_native_protocol_input_validation FAIL cidb
03636_benchmark_error_messages FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) failure
04094_mutation_checksum_mismatch_natural_trigger FAIL cidb
Stateless tests (arm_binary, parallel) failure
02555_davengers_rename_chain FAIL cidb
Stateless tests (arm_asan_ubsan, azure, parallel) failure
Sanitizer (STID: 3113-510b) FAIL cidb
Scraping system tables FAIL cidb
Stress test (amd_tsan) failure
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

This PR fixes mutation handling when part.metadata_version > table.metadata_version by postponing MUTATE_PART until ALTER_METADATA catches up, and adds a deterministic regression test. High-level verdict: the core fix looks correct, but the new test has one reliability issue that should be fixed before merge.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04094_mutation_checksum_mismatch_natural_trigger.sh:115] The test enables rmt_pause_before_apply_metadata_alter but does not guard it with cleanup on failure. With set -e, any failure before the explicit disable can leave the failpoint enabled in the server process and affect later tests in the same run.
    • Suggested fix: add trap cleanup (disable failpoint on EXIT) immediately after enabling, then optionally clear the trap once the explicit disable has succeeded.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Add failpoint cleanup in 04094_mutation_checksum_mismatch_natural_trigger.sh (trap-based disable on script exit) so failures cannot leak global failpoint state to subsequent tests.

@tiandiwonder
tiandiwonder marked this pull request as draft April 10, 2026 07:14
@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 10, 2026
Comment thread src/Storages/MergeTree/MutateTask.cpp Outdated
/// the next schema-change mutation (e.g. the ADD COLUMN materialisation) does not
/// overwrite the data that was already carried through by this mutation.
/// effective_metadata_snapshot already holds the correct max() version in that case.
ctx->new_data_part->setColumns(new_columns, new_infos, ctx->effective_metadata_snapshot->getMetadataVersion());

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.

MutateTask::prepare now builds effective_metadata_snapshot, but MutateSomePartColumnsTask still constructs MergedColumnOnlyOutputStream with ctx->metadata_snapshot.

In the subset-mutation path, MergedColumnOnlyOutputStream::fillChecksums calls new_part->setColumns(..., metadata_snapshot->getMetadataVersion()), so with a concrete state part.meta=12, table.meta=11 we still end with output part meta=11 after fillChecksums, despite ctx->new_data_part->setColumns(..., 12) earlier.

That downgrades metadata_version and can re-trigger silent overwrite on the next schema-materialization mutation.

Please pass ctx->effective_metadata_snapshot here as well (same as MutateAllPartColumnsTask) so both mutation writer paths preserve max(part, table).

@tiandiwonder
tiandiwonder force-pushed the fix-mutation-part-metadata-version-mismatch branch 2 times, most recently from 46d0eb7 to a988a45 Compare April 11, 2026 12:54
@tiandiwonder
tiandiwonder force-pushed the fix-mutation-part-metadata-version-mismatch branch from a988a45 to 53be33e Compare April 11, 2026 12:55
# r2 will NOT be affected: it already processed its ALTER_METADATA and
# won't execute it again.
# ---------------------------------------------------------------------------
$CLICKHOUSE_CLIENT -q "SYSTEM ENABLE FAILPOINT rmt_pause_before_apply_metadata_alter"

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.

SYSTEM ENABLE FAILPOINT rmt_pause_before_apply_metadata_alter is not protected by a cleanup handler. With set -e, any assertion/command failure before the explicit disable step leaves this failpoint enabled for the server process, which can contaminate later tests in the same run.

Please add a trap-based cleanup right after enabling (or at script start), e.g. trap "$CLICKHOUSE_CLIENT -q \"SYSTEM DISABLE FAILPOINT rmt_pause_before_apply_metadata_alter\" || true" EXIT, and clear the trap after successful disable if desired.

@clickhouse-gh

clickhouse-gh Bot commented Apr 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 78.00% 84.10% +6.10%
Functions 90.40% 90.90% +0.50%
Branches 70.50% 76.60% +6.10%

Changed lines: 97.83% (45/46) | lost baseline coverage: 3 line(s) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Dear @tiandiwonder, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@tiandiwonder

Copy link
Copy Markdown
Contributor Author

close it for now, will check it in future.

pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Jul 31, 2026
A part stores its metadata version on disk in metadata_version.txt and keeps it
verbatim when it is fetched from another replica (DataPartsExchange.cpp:264-266).
A replica's table metadata version, in contrast, only advances through
setTableStructure (StorageReplicatedMergeTree.cpp:1822), whose only caller is
executeMetadataAlter (:6731), so it advances only when that replica executes its
own ALTER_METADATA queue entry.

A replica can therefore hold a fetched part at metadata version 1, containing a
column the replica does not know about yet, while its own snapshot is still at
version 0. A plain data mutation such as ALTER DELETE carries alter_version = -1,
so isAlterMutation() is false and the alter_sequence gating in
shouldExecuteLogEntry does not apply to it. splitAndModifyMutationCommands then
iterates the part's columns, finds one that is absent from the table snapshot and
throws LOGICAL_ERROR at MutateTask.cpp:510, which aborts the server in debug and
sanitizer builds. The soft path just above it only covers the opposite ordering,
where the part is older than the table and the column was genuinely dropped.

This is a gap between the two subclasses of ReplicatedMergeMutateTaskBase.
MergeFromLogEntryTask::prepare already refuses to run in exactly this state
(MergeFromLogEntryTask.cpp:186-196, "ALTER_METADATA is still in progress"); the
mutation path had no equivalent. Add the same rule for MUTATE_PART entries in
ReplicatedMergeTreeQueue::shouldExecuteLogEntry, so such an entry is postponed
until the pending ALTER_METADATA is applied, after which the mutation runs
normally.

The queue predicate is used rather than MutateFromLogEntryTask::prepare so that
nothing is reserved or locked before bailing out: prepare would already have
built a FutureMergedMutatedPart, reserved disk, taken a table lockForShare,
inserted a MergeListEntry and, under zero-copy replication, possibly taken a
zero-copy lock. Writing the reason through LogToStr also surfaces it in
system.replication_queue.postpone_reason.

MutateTask.cpp is deliberately unchanged. The assertion keeps its full meaning
and the equal-versions case still throws, so this is not the soft-keep direction
of ClickHouse#96008, which was reverted in ClickHouse#97301 as a data-loss risk. ClickHouse#102349 reached the
same placement and was closed by its own author.

The guard is unconditional, matching the merge sibling, so it inherits that
guard's liveness assumption that some ALTER_METADATA eventually applies. Every
producer of the mismatch keeps or plants one, including the dummy_alter entry
that the recovery path synthesizes (StorageReplicatedMergeTree.cpp:3966-3976).

Closes: ClickHouse#91015

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[CI crash] Mutation command splitting failed during alter operation

1 participant