Skip to content

Ignore a column absent from the table when materializing TTL - #115962

Merged
Avogar merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-mutation-stale-read-column-dropped-part-column
Sep 16, 2026
Merged

Avogar merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-mutation-stale-read-column-dropped-part-column

Conversation

@groeneai

@groeneai groeneai commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115416
Related: #119354
Related: #102153
Related: #116646

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 ALTER TABLE ... MATERIALIZE TTL failing with UNKNOWN_IDENTIFIER and being retried forever on a table with ttl_only_drop_parts = 1 when a part still holds a column that the table dropped while that part's partition was detached. Mutating such a partition after cloning it into another table with ATTACH PARTITION FROM no longer fails with a logical error either.

Description

#119354 merged the same skip for the general case and closed #115416, leaving only the MATERIALIZE TTL fast path it does not reach.

With only a rows TTL and ttl_only_drop_parts = 1, MATERIALIZE TTL marked every column it does not rewrite as ignored, and an ignored column skipped the check for columns absent from the table. A partition detached before DROP COLUMN and re-attached after it still carries that column, so the split emitted a READ_COLUMN whose identifier no longer resolved, and the mutation was retried for as long as the part existed:

Code: 341 ... mutation 'mutation_4.txt' with part '1_3_3_0' reason:
'Code: 47 ... Unknown expression identifier `c`. Maybe you meant: ['p'] ... (UNKNOWN_IDENTIFIER)'

Dropping that term makes the fast path take the same decision as every other mutation command, which exposed a second case, reported in review (#102153) and folded in here: ATTACH/REPLACE PARTITION FROM and MOVE PARTITION TO TABLE stamp the destination's metadata version on a part that keeps the source's columns, so a partition cloned out of a table that had dropped the column arrives at the table's own version with a column in no schema at all, which took the logical error in the split and aborted a debug or sanitizer build. Every mutation on this path now treats an equal metadata version like a smaller one; the throw is kept only for a part AHEAD of the table, where the column is real data (#96008, reverted by #97301) and the queue already postpones the mutation.

The test has three arms, MergeTree, ReplicatedMergeTree and a cloned partition, and drops no-shared-merge-tree: every arm now takes the version comparison, not the branch that asks whether the storage is replicated. On debug builds master fails all three with UNKNOWN_IDENTIFIER, this branch without the one-line change passes the first two and aborts on the third, and with it all three pass.


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

Version info

  • Merged into: 26.9.1.1602 (included in 26.9 and later)

A mutation on a compact part could fail permanently with

  Unknown expression identifier `h` in scope d, b, h, c, a, d, b, h, c, a

and be retried by the background executor for as long as the part and the
mutation entry both existed, so the mutation never completed.

The compact / dynamic-column / non-full-storage branch of
splitAndModifyMutationCommands reconciles the part's columns against the
table's. When a part column is absent from both the table metadata and the
virtuals, the branch consults the metadata versions to decide whether the
column was dropped. That test cannot decide on a plain MergeTree, where both
versions are 0 and metadata_version.txt is written, so control fell through
and a READ_COLUMN command was emitted for the column anyway. MutateTask
builds the interpreter with the table's physical columns as the available
set, so that identifier cannot resolve and the analyzer throws.

Skip the column instead, which is what the block's own comment already says
the compact policy is, what the metadata-version path does when it can
decide, and what the wide branch has always done because it iterates the
commands rather than the part's columns.

The LOGICAL_ERROR for replicated tables is left untouched: on those engines
the metadata version is meaningful, so a part column missing from the table
is a real bug and the assertion still fires ahead of the new skip.

A column that is still in the table metadata is unaffected and keeps being
rewritten; the new test covers that as well as both part types.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two independent reviews were run against this diff before it was pushed: a cold code review
with no access to the implementation notes, and a separate second-model gate. Both were then
adjudicated against the recorded validation evidence.

Second-model gate: 0 findings. It read MutateTask.cpp in full, traced callers and sibling
paths, read the new and related tests, and checked test liveness against a pre-fix binary.

Cold review: no blockers, no majors. Three nits, all resolved against measurements rather
than carried forward:

Point Verdict
💡 The new skip's own LOG_WARNING is not asserted by the test Not a gap. h_has_files_after moves 0 to 1 between the fixed and unfixed binary on the same test file and reference, while the wide block and the still-present-column block stay byte-identical, so the assertion set is a live oracle for the changed branch. A log-message oracle was rejected deliberately: it counts its own probe query and is timing-dependent.
💡 wait_for_mutations() is hand-rolled where mergetree_mutations.lib ships wait_for_all_mutations() The library helper breaks only on is_done, so it would spend its whole timeout on the unfixed binary. This one also breaks on a non-empty latest_fail_reason, which is what lets the unfixed arm fail fast. A synchronous ALTER cannot be the oracle at all: StorageMergeTree::waitForMutation returns on the first reported failure, before the mutation has been applied to every part, so alter_sync = 2 reported unfinished_mutations = 1 on fully-mutated data.
💡 Tags are only no-shared-merge-tree, where sibling DETACH/ATTACH tests also carry no-replicated-database Correct as it stands. DatabaseReplicated does not rewrite a bare MergeTree engine, so under --replicated-database the tables stay plain and the changed branch is still taken. The one mechanism that would rewrite the engine, SharedEngineReplacer, is already excluded by no-shared-merge-tree.

Independently verified during the cold review, before reading the implementation notes:

  • The suppressed READ_COLUMN could never have resolved. The interpreter is built with the
    table's physical columns as its available set, which is a strict subset of the metadata the
    enclosing test has already found the name absent from, and none of the three places that
    extend that set can reintroduce a dropped user column. The skip removes a guaranteed failure,
    not a working read.
  • No silent data loss. A compact or packed part is rewritten in full, so its new column set comes
    from table metadata and the phantom column is dropped, which is what a merge already does and
    what the issue asks for.
  • The uninitialized-pipeline LOGICAL_ERROR cannot be reached by an emptied command list:
    entering this block requires a data mutation, which was already queued for the interpreter
    earlier in the same pass.
  • The replicated LOGICAL_ERROR is byte-identical and still precedes the new skip. Its history
    was checked: this block's replicated half was changed and then reverted, and that revert stands.
  • 04652_mutate_part_ahead_of_table_metadata_version covers the same block's metadata-version
    branch on a replicated table and is unaffected.
  • The metadata-version test really cannot decide on a plain MergeTree: that engine never sets a
    table metadata version, and the part writes metadata_version.txt, so both sides are 0 and the
    equal-versions carve-out does not apply.

One residual is disclosed rather than folded in: MATERIALIZE TTL with ttl_only_drop_parts = 1
reaches such a column through a different short-circuit that bypasses this code path entirely, and
still fails. A control at ttl_only_drop_parts = 0 fails without the fix and passes with it, which
is what shows the short-circuit is intact and the survivor is a separate carrier.

Session id: cron:clickhouse-review-slot-48:20260822-234000

@clickhouse-gh clickhouse-gh Bot closed this Aug 23, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE ... SETTINGS min_bytes_for_wide_part = 1000000000, min_rows_for_wide_part = 1000000000 + INSERT 100 rows, then DETACH PARTITION 0 / DROP COLUMN h / ATTACH PARTITION 0 / ALTER ... UPDATE b = b + 1 WHERE 1. No concurrency, no SYSTEM STOP MERGES. Issue #115416's own reproducer also fails on demand (Code: 341 UNFINISHED).
b Root cause explained? Yes. The compact / dynamic-column / non-full-storage branch of splitAndModifyMutationCommands (MutateTask.cpp:513-545) iterates the part's columns; at :517 it establishes a column is in neither the table metadata nor the virtuals nor ignored_columns, then consults the metadata versions at :527 to decide whether it was dropped. On a plain MergeTree both versions are 0 and metadata_version.txt is written, so 0 < 0 and allow_equal_versions are both false; supportsReplication() is false so the LOGICAL_ERROR at :536 does not fire either; control falls through to :543 and emits a READ_COLUMN. MutateTask::prepare builds the interpreter with the table's physical columns as available_columns (:3961), so the identifier cannot resolve and QueryAnalyzer throws UNKNOWN_IDENTIFIER. The mutation entry and part both persist, so the background executor retries indefinitely.
c Fix matches root cause? Yes. The fallthrough that manufactures the impossible command is replaced by a skip, at the producer. Not a widened bound, not a no-random-* tag, not a reduced dataset, and not a symptom catch in MutatePlainMergeTreeTask::executeStep (which would swallow genuine UPDATE/DELETE expression errors).
d Test intent preserved / new tests added? New test 04880_mutation_dropped_column_compact_part.sh added; no existing test weakened or removed. It asserts its own preconditions (part is Compact, the column has files, the column is in the part but not the metadata) so it cannot pass vacuously, and it includes a negative control for over-broadness.
e Both directions demonstrated? Yes, same test file and reference against both binaries. Fix build [ OK ]; base build [ FAIL ] with only the compact block differing: unfinished_mutations 0 -> 1, unknown_identifier_failures 0 -> 1, sum(b) 5050 -> 5000 (one partition never advanced), h_has_files_after 0 -> 1. The wide block and the still-present-column control are byte-identical between arms. Issue #115416's reproducer: base Code: 341 UNFINISHED, fix completes with 99 rows.
f Fix is general across code paths? Yes. splitAndModifyMutationCommands has exactly one call site (MutateTask.cpp:3937, inside MutateTask::prepare()), so the change covers plain, Replicated and Shared MergeTree and both analyzers from one place, and is structurally execution-only, so bad user DDL is still rejected upstream. Sibling emitters were each checked: the wide branch needs nothing (it iterates the commands, not the part's columns, so it never synthesizes such a read); extra_columns_for_indices_and_projections reads types from the table metadata and so can never name an absent column; the block-number and block-offset virtuals pass the :517 test; read_for_patch columns are user commands and never enter the loop. The user-commanded READ_COLUMN arms at :624/:302 were probed on both part types and the state is not reachable (a live mutation naming the column blocks DROP COLUMN with Code: 36; detaching every partition instead completes that mutation vacuously first), so the diff was deliberately not widened to them.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The condition is column presence in the metadata, not the column's type, so type wrappers cannot change the predicate. The test covers both part types, both partitions, and a column that is still present. 100 randomized runs (2 x 50) are clean; min_bytes_for_wide_part is randomized and load-bearing here, so the part type is pinned in CREATE TABLE and asserted in the output.
h Backward compatible? Yes. No setting is added or defaulted, so no SettingsChangesHistory.cpp entry is needed; no serialization or on-disk format change; no changed error contract on replicated engines. The behaviour change is confined to plain MergeTree, is the intended fix, and is logged as a warning.
i Invariants and contracts preserved? Yes. for_file_renames is untouched and mutated_columns is not modified, so the dropped_columns arm of the same loop is unaffected. Compact parts remove nothing from disk by design, and the new part's column set follows from what is read and written, so skipping the read is exactly the documented "don't read dropped columns" outcome: after the fix the column is absent from system.parts_columns, all 100 rows survive, and the data digest equals the wide arm's. The replicated LOGICAL_ERROR at :536 is byte-for-byte unchanged and still evaluated before the new continue, verified both by diffing those lines against the base file and by an end-to-end replicated arm whose mutation ledger and digest match base exactly.

Session id: cron:clickhouse-impl-slot-41:20260822-184900

@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f22d208]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the reported MATERIALIZE TTL retry loop on parts that still carry a dropped column, and it also broadens the missing-column skip to replicated cloned parts whose metadata version now matches the destination table. I found one blocker in that broader equal-version carve-out: on replicated ATTACH/REPLACE PARTITION FROM and MOVE PARTITION TO TABLE, an equal metadata version does not prove the extra column was dropped, so the new skip can silently rewrite renamed data to defaults instead of failing loudly.

Findings

❌ Blockers

[src/Storages/MergeTree/MutateTask.cpp:550] part_metadata_version <= table_metadata_version is too broad for cloned replicated parts. Those clone paths restamp metadata_version.txt without rewriting columns.txt, and MergeTreeData::loadPartAndFixMetadataImpl already documents why overwriting the version is unsafe for parts detached before schema changes such as RENAME COLUMN. A source partition can therefore be cloned into a fresh destination with an equal metadata version and an old physical column name. This branch will skip the old name as if it were dropped, and the destination reader will default-fill the current name during the rewrite because it has no rename conversion for it, turning a loud inconsistency into permanent data loss.

Suggested fix: reject ATTACH/REPLACE/MOVE of parts that still depend on pending metadata mutations, or narrow the skip so equal versions are accepted only for a state you can prove is drop-only. Add a focused regression that clones a part stale across RENAME COLUMN into another replicated table and runs a full-rewrite mutation.

Final Verdict

Status: ⚠️ Request changes

Minimum required actions: close the equal-version stale-rename hole above, or otherwise prove that cloned replicated parts reaching this branch cannot still depend on pending metadata mutations. Add a focused regression test for that carrier.

LLVM Coverage Report

Measured on commit f22d208.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 80.50% 80.50% +0.00%

Changed lines: Changed C/C++ lines covered: 20/25 (80.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @tiandiwonder, could you review this? The compact-part branch of splitAndModifyMutationCommands finds a part column absent from table metadata, cannot decide from the metadata versions on a plain MergeTree (both are 0), and then emits a READ_COLUMN for it anyway, so the mutation fails UNKNOWN_IDENTIFIER forever. This skips the column there instead, which is what the block's own comment says the compact policy is; the replicated LOGICAL_ERROR above it is byte-identical and still fires first, so the revert in 8534e13 stands.

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit f22d208e1d88d53e158a2f12fc6937e9563c1154 with master failed: RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes W….

See the job log for details.

The previous commit skipped reading a part column the table no longer has, but
only when the column was not in ignored_columns. MATERIALIZE TTL with
ttl_only_drop_parts = 1 pre-populates ignored_columns with every non-mutated
part column, so the absent-column test was bypassed and the loop still emitted
READ_COLUMN for a dropped column. The mutation then failed UNKNOWN_IDENTIFIER
forever, the same way it did before, on the same detach / drop / re-attach shape.

The ignored_columns term is dropped from that test. It cannot mask a working
read: for a column still present in table metadata the first clause already
decides, so the term only ever applied to a column absent from metadata, and
such a read cannot resolve at all because the interpreter is built with
available_columns = getColumns().getNamesOfPhysical().

The term was moved into this inner condition by 83dcc26 ("correct set
of columns on materialize ttl for compact parts when ttl_only_drop_parts=1"),
to stop an ignored column being dropped from the new part's column set. That
property is unaffected here, because it concerns columns that are still in the
metadata.

Extends 04880 with a MATERIALIZE TTL case. Verified both directions through
clickhouse-test: it fails on the previous commit and passes with this one, with
the part type, surviving rows and metadata-absence preconditions all asserted,
and the row digest unchanged.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 188fa2c

CI is fully finished on this head and nothing failed, so no line needs an owner.

Check / test Reason Owner / fixing PR

Measured at this head: 172 distinct checks, 0 incomplete, 0 failing. The praktika aggregator is
OK at the top level (174 nodes: 156 OK, 18 SKIPPED, 0 DROPPED), with Config Workflow,
Style check and Finish Workflow all successful. CIDB agrees independently: 287485 rows at
this sha, 0 FAIL and 0 ERROR. The 18 skipped nodes are the usual non-applicable matrix legs, not
lost coverage for this diff: the new test 04880 ran on the stateless legs.

This head is the bot change-request fix (the MATERIALIZE TTL fast path reaching a column absent
from table metadata), pushed over adc034b and already answered in that review thread.

Session id: cron:our-pr-ci-monitor:20260823-090000

@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 4, 2026
…read-column-dropped-part-column

# Conflicts:
#	src/Storages/MergeTree/MutateTask.cpp
ClickHouse#119354 landed the same skip for the general case, so all that is left of this
PR is the fast path that MATERIALIZE TTL takes. With a rows-only TTL and
ttl_only_drop_parts, the command split marked every column it does not rewrite
as ignored, and an ignored column bypassed the check for columns the table no
longer has, so a partition detached before DROP COLUMN and re-attached after it
still wedged the mutation queue through that one command:

  Code: 341 ... mutation 'mutation_4.txt' with part '1_3_3_0' reason:
  'Code: 47 ... Unknown expression identifier `c`. Maybe you meant: ['p'].
   In scope id, val, p, ts, c, c, ts, p, val, id. (UNKNOWN_IDENTIFIER)' ... (UNFINISHED)

Dropping that term takes the decision the other mutation commands already take,
including the deliberate logical error on a replicated part whose metadata
version does not explain the extra column.

ignored_columns had this one reader, so the set, the loop that filled it and the
suitable_for_ttl_optimization parameter that gated it are removed as well; the
caller keeps its own local for drop_expired_parts. The set was moved into that
condition by 83dcc26 to keep the rewritten part's column set correct,
which concerns columns the table still has, and those never reach the branch.

Measured on master at 5a49d1b, which carries ClickHouse#119354: the new test fails
5/5 without the change and passes 10/10 with it, while 05202 (ClickHouse#119354's own
test) and 03285_materialize_ttl_only_drop_parts pass either way.

The four-arm shell test is replaced by that single SQL case, because 05202 now
covers the compact and wide DELETE/UPDATE arms it used to share.
@groeneai groeneai changed the title Do not read a part column that the table no longer has Ignore a column absent from the table when materializing TTL Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

#119354 merged the same MutateTask.cpp hunk this PR carried and closed #115416, so I merged master and cut this PR down to what that fix does not reach: the MATERIALIZE TTL fast path.

Measured on master at 5a49d1bd3315c, debug build, both directions (Build-IDs 3e83131e... for master as-is, 62597a88... with the change):

  • of the four arms this PR used to test, only the MATERIALIZE TTL one still reds on master: ttl_unfinished_mutations 0 -> 1, ttl_unknown_identifier_failures 0 -> 1, and the dropped column still on disk afterwards. The compact, wide and still-present-column arms pass, so Ignore a column absent from the table when mutating a Compact part #119354 owns those.
  • the new 05210_materialize_ttl_of_attached_part_with_dropped_column: 5/5 red on master, 10/10 green with the change. 05202 and 03285_materialize_ttl_only_drop_parts pass either way, as do the other tests that set ttl_only_drop_parts.

The mechanism is that under a rows-only TTL with ttl_only_drop_parts = 1 the split puts every column it does not rewrite into ignored_columns, and that set excluded a column from the absent-from-table check, so the new continue was never reached and a READ_COLUMN was still emitted for the dropped column.

The diff is now one line plus a 43-line SQL test. That check was the set's only reader, so the set, the loop that filled it and the parameter gating it are removed with it. The four-arm shell test is gone, since 05202 covers its compact and wide arms.

@Avogar Avogar self-assigned this Sep 15, 2026
@Avogar

Avogar commented Sep 15, 2026

Copy link
Copy Markdown
Member

Dropping ignored_columns routes MATERIALIZE TTL into the LOGICAL_ERROR at MutateTask.cpp:558, and that state is reachable with plain SQL, so a failed mutation becomes a server abort on debug/sanitizer builds. Verified on the binary from this PR (008b895f, debug): the server goes down, system.crash_log has signal 6 with query_id = the mutation task on that part and stack abortOnFailedAssertion -> Exception::Exception -> splitAndModifyMutationCommands (MutateTask.cpp:558) -> MutateTask::prepare -> ReplicatedMergeMutateTaskBase::executeImpl. The MUTATE_PART entry is in Keeper, so it replays on restart.

Repro
-- t_src: part carries a phantom column `c`, part metadata version 1 < table 2
CREATE TABLE t_src (id UInt64, val UInt64, p UInt8, ts DateTime) ENGINE = ReplicatedMergeTree('/t_src', '1')
PARTITION BY p ORDER BY id TTL ts + INTERVAL 30 YEAR
SETTINGS ttl_only_drop_parts = 1, min_bytes_for_wide_part = 1000000000, min_rows_for_wide_part = 1000000000;
ALTER TABLE t_src ADD COLUMN c UInt32;
INSERT INTO t_src SELECT number, number, 1, now(), 42 FROM numbers(100);
ALTER TABLE t_src DETACH PARTITION 1; ALTER TABLE t_src DROP COLUMN c; ALTER TABLE t_src ATTACH PARTITION 1;

-- t_dst: same structure, never altered, so its metadata version stays 0
CREATE TABLE t_dst (...same...) ENGINE = ReplicatedMergeTree('/t_dst', '1') ...;
ALTER TABLE t_dst ATTACH PARTITION 1 FROM t_src;  -- part stamped mv 0 == table mv 0, still carries `c`
ALTER TABLE t_dst MATERIALIZE TTL SETTINGS mutations_sync = 2;  -- abort

ATTACH/REPLACE PARTITION FROM and MOVE PARTITION TO TABLE stamp the destination's metadata version on the cloned part (metadata_version_to_write) while keeping the source part's columns.txt, so part_metadata_version == table_metadata_version holds with the column still present, and allow_equal_versions is false because the part does have a version file.

The guard conflates two opposite cases. part_mv > table_mv means the replica is behind an ALTER ADD COLUMN and the column is real - that is why #96008 was reverted by #97301 ("replace LOGICAL_ERROR with potential dataloss") - and it is now postponed before reaching here by fcb45f4 (ReplicatedMergeTreeQueue.cpp:1929). part_mv == table_mv is the clone above, where the column is in no schema at all, since those commands reject differing structures with INCOMPATIBLE_COLUMNS. So the equal case can take the same continue as the non-replicated path, keeping the throw for > only:

-   bool allow_equal_versions = part_metadata_version == table_metadata_version && part->old_part_with_no_metadata_version_on_disk;
-   if (part_metadata_version < table_metadata_version || allow_equal_versions)
+   if (part_metadata_version <= table_metadata_version)

This is pre-existing rather than introduced here - tracked as #102153, and ALTER ... DELETE on the same state already takes MutateTask.cpp:558 on master, since without MATERIALIZE_TTL the ignored_columns set is empty - but this PR adds MATERIALIZE TTL to it, so I would fold the one-liner in with a replicated test arm. Separately, #67799 is closed as resolved by #96008, which was reverted.

Two notes on the test: this PR also repairs plain ReplicatedMergeTree (the same repro minus the ATTACH PARTITION FROM fails with UNKNOWN_IDENTIFIER before it and passes after, via the part_mv < table_mv branch), so that deserves an arm; and for the same reason the no-shared-merge-tree rationale - that the branch "is reached only when the storage has no metadata version to reason with" - is not accurate.

@Avogar Avogar left a comment

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.

See the comment above

`splitAndModifyMutationCommands` tolerated a part column that the table no
longer has only when the part was behind the table's metadata version, or when
it carried no metadata version on disk at all. `ATTACH`/`REPLACE PARTITION FROM`
and `MOVE PARTITION TO TABLE` stamp the destination's metadata version on a part
that keeps the source's `columns.txt` (`metadata_version_to_write` in
`executeReplaceRange`, `replacePartitionFromImpl` and `movePartitionToTable`)
and require matching structures, so a partition cloned out of a table that had
dropped the column arrives with `part_metadata_version ==
table_metadata_version` and a column that is in no schema at all. That reached
the logical error, which is an abort on a debug or sanitizer build, and the
`MUTATE_PART` entry replays from Keeper after the restart.

The throw is kept for `part_metadata_version > table_metadata_version`, where
the replica is behind an `ALTER ADD COLUMN` and the column is real data: that is
the case ClickHouse#96008 turned into a logical error and ClickHouse#97301 reverted as "replace
LOGICAL_ERROR with potential dataloss", and `ReplicatedMergeTreeQueue` now
postpones the mutation before it can get here.

The test gains a `ReplicatedMergeTree` arm and a cloned-partition arm, and drops
`no-shared-merge-tree`: with the change every arm takes the version comparison,
which does not consult `supportsReplication()`. Measured on debug builds, per
arm (`MergeTree` / `ReplicatedMergeTree` / cloned by `ATTACH PARTITION FROM`):

    master @ 45efaa4  FAIL / FAIL / FAIL   Code: 47, retried forever
    this branch, no fix     OK   / OK   / ABORT  signal 6, split... -> prepare
    this branch             OK   / OK   / OK     part-vs-table mv 0/0, 1/2, 0/0

Reported on the PR, with the repro and the one-line diff, by Avogar.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Folded in, all three, in f22d208.

  1. Done as written: the guard is part_metadata_version <= table_metadata_version, with the throw kept for > only.

  2. 05210 has three arms now, and I measured which branch each one actually reaches rather than assuming it (system.tables.metadata_version plus the part's own metadata_version.txt):

arm table mv part mv c on the part
MergeTree, detach / drop / attach 0 0 yes
ReplicatedMergeTree, detach / drop / attach 2 1 yes
cloned by ATTACH PARTITION FROM 0 0 yes

Debug builds, per arm: master fails all three with Code: 47 ... Unknown expression identifier 'c'. Maybe you meant: ['p']. In scope id, val, p, ts, c, c, ts, p, val, id, retried forever; this branch without the one-liner passes the first two and aborts on the third (Part 1_1_1_0 with metadata version 0 contains column c that is absent in table ... with metadata version 0, signal 6, the runner sees ATTEMPT_TO_READ_AFTER_EOF); with it all three pass.

  1. The rationale was wrong, so I dropped the tag instead of rewording it: with the one-liner every arm takes the version comparison and none reaches the supportsReplication() branch (6/6 Ignoring column c from part ... with metadata version ... in the log, 0 on the other one). The tags are zookeeper, no-replicated-database now, the second because the arms name their Keeper path explicitly and database_replicated_allow_replicated_engine_arguments defaults to 0. I cannot see the Cloud run, so if SharedMergeTree disagrees the tag goes back.

The description and the changelog entry now state that the equal-version case is accepted for every mutation on this split path, not only MATERIALIZE TTL, and Related: #102153 is on the PR. #67799 is the > shape (part 13, table 12), which fcb45f4 now postpones in the queue instead of throwing, so this change does not cover it.

/// `ATTACH`/`REPLACE PARTITION FROM` and `MOVE PARTITION TO TABLE` stamp the destination's
/// version on a part that keeps the source's columns and require matching structures, so
/// an equal version with the column absent means it is in no schema at all.
if (part_metadata_version <= table_metadata_version)

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.

part_metadata_version <= table_metadata_version is not enough evidence that this extra column was dropped. In replicated ATTACH/REPLACE PARTITION FROM and MOVE PARTITION TO TABLE, cloneAndLoadDataPart rewrites metadata_version.txt on the clone but keeps the source columns.txt (src/Storages/StorageReplicatedMergeTree.cpp, src/Storages/MergeTree/MergeTreeData.cpp); MergeTreeData::loadPartAndFixMetadataImpl already documents why overwriting the version is unsafe for parts detached before schema changes such as RENAME COLUMN (src/Storages/MergeTree/MergeTreeData.cpp).

A concrete carrier is: re-attach in the source table a part that still stores a while the current schema reads it as b through a pending RENAME COLUMN, then ATTACH PARTITION FROM into a fresh replicated table whose current schema also has b. The clone arrives here with part_mv == table_mv, this branch skips a as if it were dropped, and the full rewrite default-fills b because the destination has no rename conversion for it. Before this change that state failed loudly at the LOGICAL_ERROR; with the new <= branch it can silently rewrite the renamed data to defaults.

I think this needs a stronger proof than equal metadata versions, or a guard that refuses ATTACH/REPLACE/MOVE of parts that still depend on pending metadata mutations. A focused regression for the stale-rename carrier would also help pin this down.

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 carrier reproduces, and it does land in a real defect, but not one this change introduces: the destination already answers the renamed column with defaults before any mutation exists, on master too.

Fixture: replicated bc_src(id, a, val, p), partition detached, RENAME COLUMN a TO b, partition re-attached; bc_dst(id, b, val, p) never altered; ATTACH PARTITION 1 FROM bc_src; then ALTER TABLE ... UPDATE val = val + 0 so the guard is reached without MATERIALIZE TTL. Oracle is sum(b) over 10 rows: 10045 means the renamed data survived, 0 means default-filled. Same script, three debug binaries.

master 45efaa4356741 this branch without the one-liner with it
source table reads b 10045 10045 10045
clone: part columns, table mv / part mv ['a','id','p','val'], 0 / 0 same same
clone reads b, no mutation issued yet 0 0 0
source table reads b after a mutation on it 10045 10045 10045
clone reads b after a mutation on it abort, signal 6 abort, signal 6 0

So the rewrite default-fills nothing. sum(b) on the clone is 0 the moment ATTACH PARTITION FROM returns and it is still 0 afterwards; what the <= branch changes is only that the unreadable a bytes leave the disk instead of the mutation aborting the server. The loud failure was not guarding a value any query could reach, and the carrier is itself one more instance of the abort this change removes.

The < case is not exposed either. In the source table the rename is still an unapplied metadata mutation for that part, so RENAME_COLUMN is in the part's command list and the DROP_COLUMN/RENAME_COLUMN branch of the same helper puts a into mutated_columns, which means the missing-column guard is never reached: the file is renamed and sum(b) stays 10045 (part columns go from ['a', ...] to ['b', ...]). The log carries exactly one Ignoring column line, for the clone, and none for the source.

That is also why a stronger predicate cannot live at this site. By the time the split runs, the part is in a table whose mutation history never saw the rename, so nothing in the destination records that a was ever b; the discriminating information exists only at clone time, where cloneAndLoadDataPart stamps the destination's version over the source's unapplied conversion. So the second half of the suggestion is the right one and the guard belongs on ATTACH/REPLACE/MOVE. #116646 is the same skipped-conversion outcome from a different trigger, a missing metadata_version.txt; it is on the PR as Related: now and I am not fixing it here.

On the focused regression: written against this branch it would have to assert sum(b) = 0, which pins the pre-existing wrong result as expected behaviour. The assertion worth having is 10045, or a refusal at ATTACH PARTITION FROM, and it belongs with the fix at that layer.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f22d208

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.

CI is fully finished on this head: 176 checks, 155 pass, 18 skipped, 2 failed,
aggregator complete, and nothing left running except CH Inc sync. The last real check completed at
18:45:30Z, well past the 20 minute buffer the CI database needs.

Check / test Reason Owner / fixing PR
Build profile diff infra, nothing tested: has_pr_data raised RuntimeError: CI logs cluster query failed on the binary_sizes read and aborted the job before any comparison ran #120121 (mine, open), which turns a transient cluster read failure into a skipped comparison instead of a failed one
CH Inc sync still pending: the private mirror sync does not complete on a fork CH Inc sync (private, not actionable by me)

PR aggregate the rows above rather than adding a failure of their own.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115962&sha=f22d208e1d88d53e158a2f12fc6937e9563c1154&name_0=PR

Session id: cron:our-pr-ci-monitor:20260915-190256

@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 9f22e3a5-3ea3-45aa-92fa-bd0bbd9c6b81
  • MIRAI run: cb212d9f-ec34-4dd8-8170-8f87e040cf95
  • PR check IDs:
    • clickbench_429239_1789565691
    • clickbench_429245_1789565691
    • clickbench_429256_1789565691
    • tpch_adapted_1_official_429263_1789565691
    • tpch_adapted_1_official_429295_1789565691
    • tpch_adapted_1_official_429309_1789565691

@Avogar
Avogar added this pull request to the merge queue Sep 16, 2026
Merged via the queue into ClickHouse:master with commit 307af81 Sep 16, 2026
175 of 177 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 16, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
`05210_materialize_ttl_of_attached_part_with_dropped_column`, merged with
ClickHouse#115962, clones a partition whose source part carries an unapplied
`DROP COLUMN` conversion and asserts that the clone succeeds. The guard added
here refused it, so merging master into this branch turned `Fast test` red.

An unapplied conversion reaches a reader only through a column the table still
has: a `RENAME COLUMN` is read under its new name, which the part does not
store, and a `DROP COLUMN` masks the part's stale data for a column of that
name. When the column is in neither schema, which is what a partition detached
before a plain `DROP COLUMN` and re-attached after it leaves behind, nothing
resolves to it and the clone just carries a column no reader asks for. Master
already keeps that state on a same-table re-attach (ClickHouse#96351 made it preserve the
part's own metadata version), so refusing only its cross-table twin rejected a
valid command and contradicted the same-table behaviour.

The predicate therefore resolves each column of the table the way a reader
resolves it: the rename lookup, the part's own carriers for the name it
resolves to, and `isColumnDropped` with the table's `share_nested_offsets`,
which decides whether dropping `n` also drops the part's `n.a`. A column
skipped by `skip_empty_columns_on_insert` has no files and is read from its
marker in `serialization.json`, so it is a carrier as well, and like the reader
the guard discards that marker when either the part-time name or the current
one was dropped. A part is refused only where that resolution and the
destination's plain read of the same name disagree, which is what makes the
refusal exactly as wide as the wrong answer it prevents. `CLEAR COLUMN` is a
`DROP_COLUMN` carrying `clear`, and a merge writes its defaults without
discharging the command, so the refusal names the mutation for it instead of
naming OPTIMIZE.

Seven cases in the test pin that boundary, each measured to change outcome when
the resolution is weakened. Three are refused: a part holding both names of a
rename, where the source reads the renamed column and a clone reads the part's
own stale one (70 against 10045); a `Nested` parent dropped and re-added, whose
shared offsets make the part's subcolumn data stale as well (0 against 45); and
a column skipped on insert, then dropped and re-added with a `DEFAULT`, where
the source evaluates that default and a clone honours the marker (9990 against
0). Four are cloned: a `DROP COLUMN` whose column is in neither schema, which
this guard refused before; a `RENAME COLUMN` of a column the part never stored;
a dropped dotted prefix under `share_nested_offsets = 0`; and a marker that the
drop of the current name invalidates, where both sides read 5550. A pending
`CLEAR COLUMN` gets its own refusal arm. The file also declares the `zookeeper`
tag that its `ReplicatedMergeTree` sources need.
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-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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.

Re-attached partition carrying a since-dropped column permanently wedges the mutation queue (UNKNOWN_IDENTIFIER); KILL MUTATION does not recover

3 participants