Skip to content

Fix data loss when a merge races ALTER RENAME COLUMN on a column without a default expression - #109356

Merged
Avogar merged 23 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-80648-residual-dynamic-expired-columns
Jul 30, 2026
Merged

Avogar merged 23 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-80648-residual-dynamic-expired-columns

Conversation

@groeneai

@groeneai groeneai commented Jul 3, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fix data loss of a column with no default expression when a merge runs concurrently with ALTER TABLE ... RENAME COLUMN, or when the column's only values come from a lightweight UPDATE. The column could be dropped from the merged part, so all of its values read back as NULL.

Description

Follow-up to #104822 (primary fix for #80648), which closed the data-loss window for columns with a default expression but left a residual for columns without one.

A merge applies a pending RENAME COLUMN old -> new on-fly at read time: storage_columns already carries new, while the source parts still physically store old. MergeTask's expired-columns optimization compared storage_columns against the parts' raw physical names and, finding new absent from every part, treated it as an expired column. A column with no default expression is then dropped from the merged part, so every value reads back as NULL. Columns with a default (for example String DEFAULT '') are refilled from the default, which is why #104822 handles them but not columns without one.

Fix: when scanning for expired columns, treat a rename target as present whenever a source part physically holds the matching old name, using the alter_conversions rename map the merge already uses to apply the rename on-fly. A genuinely dropped column, absent from all parts, still expires as before. Merge selection, part naming and mutation-version stamping are untouched.

The same scan had a second carrier: it only looked at the base parts, so a column added by ADD COLUMN and then filled by a lightweight UPDATE - whose only values live in a patch part selected for the merge - was expired too, and the patch never requested (no rename needed to reproduce). The scan now also considers the selected patch parts' physical columns, both for the column's own name and for a pending rename target.

A new test 04648_alter_rename_column_no_default_merge_race pins both carriers with a deterministic reproducer (failpoint-pinned pending rename + OPTIMIZE FINAL), covering a plain column, a Dynamic column, a rename target whose old name is re-added first, and the patch-part cases. The existing 04238_alter_rename_column_merge_race is left untouched.

Closes #111001

Version info

  • Backported to: 26.7.2.51, 26.6.2.138, 26.5.6.97, 26.3.17.97, 25.8.29.50

…NAME COLUMN

A merge applies a pending RENAME COLUMN to its source parts on-fly at read
time: the metadata (and storage_columns) already carries the new name, while
the source parts still physically store the old name. MergeTask's
expired-columns optimization compared storage_columns against the parts' raw
physical names and, finding the new name absent, treated it as an expired
column. A column with no default expression (e.g. Dynamic) was therefore
dropped from the merged part, so every value read back as NULL. See ClickHouse#80648.

Fix: when scanning for expired columns, treat a rename target as present
whenever a source part physically holds the matching old name (via the same
alter_conversions rename map the merge already uses to apply the rename
on-fly). A genuinely dropped column, whose old name is absent, still expires.

The pending-mutations snapshot is computed once and reused by both the
expired-columns check and the later alter_conversions/patch handling so both
observe the same mutation set.

Residual facet of ClickHouse#80648 that the primary fix (ClickHouse#104822, atomic metadata +
pending-mutation publication) does not close: that fix handles columns with a
default (the String case), which are refilled rather than dropped. Adds the
Dynamic-phase regression test to 04238_alter_rename_column_merge_race.

Related: ClickHouse#104822

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. RENAME COLUMN d TO d1 SETTINGS alter_sync=2 racing OPTIMIZE TABLE t FINAL on a Dynamic (no-default) column loses data at ~0.25% per iteration on local disk (2/800 measured without the fix). Reproducer is the second phase added to 04238_alter_rename_column_merge_race.sh.
b Root cause explained? Yes. A merge applies a pending RENAME COLUMN old -> new on-fly at read time: metadata (and storage_columns) already carry new, but source parts still physically store old. MergeTask's expired-columns check compares storage_columns against the parts' raw physical names, finds new absent from every part, and (because a Dynamic column has no default to refill it) marks it expired and drops it from the merged part, so every value reads back NULL.
c Fix matches root cause? Yes. When scanning for expired columns, treat a rename target as present whenever a source part physically holds the matching old name, via the same alter_conversions rename map the merge already uses to apply the rename on-fly. This directly addresses the "new name absent from parts" mismatch from (b).
d Test intent preserved / new tests added? Yes. New regression test added (Dynamic no-default phase in 04238). The existing String DEFAULT '' phase is unchanged and still passes. No existing assertion weakened.
e Both directions demonstrated? Yes. Without fix: 2/800 losses (Dynamic, local disk). With fix (rebased onto merged master, Build ID verified): 0/400 losses; the String phase remains 0 losses.
f Fix is general across code paths? Yes. The guard is in the single expired-columns site in MergeTask::ExecuteAndFinalizeHorizontalPart::prepare(); there is no sibling expired-columns path. It fixes the cause (the physical-vs-metadata name mismatch), not a symptom — a genuinely dropped column (old name absent from all parts) still correctly expires.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The fix is type-agnostic: it protects any renamed column whose target lacks a default, so Dynamic, JSON/Object, Variant, or a plain no-default column are all handled by the same rename-map lookup. It does not branch on column type. Columns with a default were already handled by #104822.
h Backward compatible? Yes. No setting default, on-disk/wire format, replication metadata, or validation change. Pure correctness fix in the in-memory merge path; no SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. The pending-mutations snapshot is now computed once (before the expired-columns check) and reused for the later patches/alter_conversions handling, so both observe the same mutation set. Merge-selection, part naming, and mutation-version stamping are untouched (deliberately not the version-stamping approach that regressed core-merge tests in earlier attempts). Merged-part block-structure and column-set invariants are preserved: the fix only prevents an on-fly-renamed column from being wrongly excluded.

Session id: cron:clickhouse-worker-slot-4:20260703-191500

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CurtizJ — could you review this? It is the follow-up to #104822 for #80648: a merge that races ALTER RENAME COLUMN drops a no-default column (e.g. Dynamic) from the merged part because the expired-columns check sees the new name in metadata but only the old name physically present in the source parts. The fix treats a rename target as present when a source part holds the matching old name, using the same alter_conversions rename map the merge already applies on-fly. No merge-selection / part-naming / version-stamping change.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [56319e1]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Filter column A not found in DAG outputs: [B] (STID: 3434-5828) FAIL cidb

AI Review

Summary

This PR fixes the single-rename and patch-only expired-columns cases in MergeTask, but it still leaves correctness gaps in rename-reuse scenarios. I cannot approve it yet because a compound pending RENAME COLUMN can still lose data, and the already-open reuse/read-path issue is still present in the current code.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTask.cpp:728-731] The new keep-alive still fails for compound RENAME COLUMN mutations such as RENAME COLUMN a TO c, RENAME COLUMN b TO a. storage_column_names.contains(rename.rename_from) treats the intermediate a as if it were a genuinely re-added live column, so c is not kept alive and a no-default a is still expired out of the merged part. With a default on c, the merged part is written under the post-rename names while keeping the pre-rename mutation version, so the later mutation re-applies the rename and hits the existing-target guard instead. Suggested fix: distinguish “re-added old name” from “old name is another pending rename target” before suppressing the keep-alive, and add a reproducer for the multi-rename form.

⚠️ Majors

  • [src/Storages/MergeTree/MergeTask.cpp:728-744; src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp:105-123; src/Storages/MergeTree/AlterConversions.cpp:292-308] The rename-reuse path still leaves the re-added old name readable from the stale on-disk column until the pending rename mutation materializes. MergeTask now expires b, but the read side still maps logical b back to physical a and does not treat that physical a as stale for direct lookup of logical a, so both names can read the same bytes in the interim window. Suggested fix: once a pending rename claims rename_from for rename_to, direct lookup of rename_from needs the same stale-column treatment that DROP COLUMN/re-add already gets.
Final Verdict

Request changes.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 3, 2026
The probabilistic race (25 iterations at ~0.25% per iteration) caught the
residual no-default facet of ClickHouse#80648 only about 6% of the time, so a green CI
run did not meaningfully guard against a regression.

Force the exact window deterministically instead, using the same idiom as
03830_vertical_merge_inject_column_after_drop: the
mt_select_parts_to_mutate_no_free_threads failpoint keeps the RENAME mutation
from being selected, so the source parts stay physically at the old column
name while the metadata already carries the new one; alter_sync=0 returns right
after the metadata commit; OPTIMIZE FINAL then merges the still-old parts under
the new metadata and applies the rename on-fly. That is exactly the path that
dropped a no-default column. Disable the failpoint afterwards and wait for the
pending mutation to materialize before the final read.

Both phases are now deterministic (no iteration loop, no long tag): the Dynamic
no-default phase fails every run without the fix and passes every run with it;
the String DEFAULT '' phase continues to pass.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SYSTEM ENABLE FAILPOINT mt_select_parts_to_mutate_no_free_threads, then ALTER ... RENAME COLUMN d TO d1 SETTINGS alter_sync = 0, then OPTIMIZE TABLE ... FINAL. Fires the expired-columns path on every run.
b Root cause explained? Yes. The failpoint stops the RENAME mutation from being selected, so source parts keep the old physical name while metadata already carries the new one; alter_sync=0 returns after the metadata commit; OPTIMIZE FINAL merges the still-old parts under the new metadata and applies the rename on-fly, which is exactly the window where the expired-columns scan dropped the no-default column.
c Fix matches root cause? N/A for this change (the code fix landed in fa947f7). This commit only makes the existing regression test deterministic; it does not alter the fix.
d Test intent preserved / new tests added? Yes. The Dynamic no-default phase (the residual #80648 facet) now catches the regression on every run instead of ~6%; the String DEFAULT '' phase (the #104822 facet) is retained. No test coverage removed.
e Both directions demonstrated? Yes. Debug build: without the fix the Dynamic phase reads 0/8 non-null every run (20/20); with the fix 8/8 every run (25/25).
f Fix is general across code paths? N/A (test-only change, no code bug fixed here).
g Fix generalizes across inputs? N/A (test-only change). The test itself covers both a no-default column (Dynamic) and a defaulted column (String DEFAULT '').
h Backward compatible? N/A (test-only change; no settings, formats, or behavior changed).
i Invariants and contracts preserved? N/A (test-only change). The failpoint is disabled and the pending mutation is awaited before the final read, so the table is left in a consistent state.

Session id: cron:clickhouse-worker-slot-2:20260703-212800

The final SELECT is only meaningful after the pending RENAME COLUMN mutation
has materialized: reading the renamed column while its mutation is still
pending returns NULL regardless of the fix. Give wait_mutation a larger budget
and, on timeout, print the still-pending mutations and return non-zero so a
slow-worker case surfaces as a timeout instead of falling through to the
pre-materialization NULL, which would look like a false data-loss regression.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The rewritten String DEFAULT '' and Dynamic no-default count checks only
printed diagnostics and fell through to echo OK, so a wrong count still
exited 0 on the exact data-loss path the test guards. Add exit 1 after
dumping the offending rows in both mismatch branches, matching the old
loop, so a regression is a hard failure.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The test arms the server-global failpoint mt_select_parts_to_mutate_no_free_threads
and relied on an explicit SYSTEM DISABLE FAILPOINT later in the flow. Under set -e,
a failure in ALTER, OPTIMIZE or wait_mutation before that disable would exit the
script with the failpoint still armed, so every later stateless test on the same
server inherits postponed mutations (a poisoned-server leak, in both phases).

Move the disable into a disable_failpoint helper wired to a trap ... EXIT so the
failpoint is cleared on every exit path, including the set -e abort and the
wait_mutation timeout return 1. The in-flow disables stay (the pending rename
mutation only materializes once the failpoint is off, which wait_mutation needs);
they now call the same helper. The EXIT trap does not mask the failure: bash keeps
the pending non-zero status through the trap, so a real regression still surfaces
as a test failure.

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

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 9198d5b

CI fully finished on this head: all non-exempt checks passed, zero failures. The only non-passing check is CH Inc sync (private ClickHouse Inc sync, not actionable by us). No failure needs an owner; the PR is ready for review.

Check / test Reason Owner / fixing PR
Sync - CH Inc sync (private, not actionable)

(The 04238 Bugfix-validation failures seen earlier were on superseded force-pushed commits fa947f72/fc6fbe69; Bugfix validation and the full stateless/stress/integration matrix are green on the current head 9198d5b.)

Session id: cron:our-pr-ci-monitor:20260704-053000

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@alexey-milovidov alexey-milovidov self-assigned this Jul 12, 2026
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@Avogar Avogar self-assigned this Jul 14, 2026
@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-bugfix Pull request with bugfix, not backported by default labels Jul 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

This also fixes a second, crashier manifestation of the same expired-columns-vs-RENAME-COLUMN bug: on a single-column ORDER BY tuple() table, the renamed column is the only column, so expiring it leaves a zero-column merged part and the merge aborts with

Logical error: Cannot calculate columns sizes when columns or checksums are not initialized
  IMergeTreeDataPart::calculateColumnsSizesOnDisk (IMergeTreeDataPart.cpp:2691)
  <- MergedBlockOutputStream::finalizePartAsync (MergedBlockOutputStream.cpp:253)
  <- MergeTask::MergeProjectionsStage::finalizeProjectionsAndWholeMerge

Found by BuzzHouse (arm_asan_ubsan), STID 4909-6cd4: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107091&sha=5e31ccb31390e87186ca0a7a5a047aec6968c392&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29 (rare pre-existing finding, 0 master hits).

Deterministic repro on master, and it passes with this PR's change:

CREATE TABLE t (c0 UInt256) ENGINE=MergeTree ORDER BY tuple() PRIMARY KEY tuple();
INSERT INTO t VALUES (1);
INSERT INTO t VALUES (2);
SYSTEM ENABLE FAILPOINT mt_select_parts_to_mutate_no_free_threads;
ALTER TABLE t RENAME COLUMN c0 TO c1 SETTINGS alter_sync=0;
OPTIMIZE TABLE t FINAL;   -- aborts on master, ok with this PR

Comment thread src/Storages/MergeTree/MergeTask.cpp Outdated
auto conversions = MergeTreeData::getAlterConversionsForPart(part, mutations_snapshot, global_ctx->context);
for (const auto & rename : conversions->getRenameMap())
{
if (columns_present_in_parts.contains(rename.rename_from))

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 the old name is reused before the RENAME COLUMN mutation materializes, this still misbinds data. RENAME a -> b is a barrier, but a later non-barrier ADD COLUMN a ... does not wait for that pending rename (StorageMergeTree::alter only waits when the current ALTER contains a barrier), so a merge can see metadata with both a and b while the source parts still physically store only the pre-rename a.

In that state this loop keeps b alive, but the read path then maps logical b back to physical a (MergeTreeBlockReadUtils.cpp, getColumnOldName) while logical a is also treated as the same physical a, because pending renames do not make rename_from look stale the way pending DROP COLUMN does. The merged part will therefore read the old bytes into both columns instead of defaulting the re-added a.

Can we also mark rename_from as unavailable for direct lookup once a pending rename claims it (or otherwise distinguish a re-added old name), so the old on-disk column can back only b and not both names?

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 fixed in 1f934b6.

You are right that re-adding the old name before the pending RENAME materializes is a real problem, and I reproduced it deterministically (failpoint mt_select_parts_to_mutate_no_free_threads + alter_sync=0, same idiom as the existing phases). The manifestation is a bit sharper than a silent read: keeping b alive off the physical a while a is also re-added makes the merged part carry both a and b from one physical column, and the pending rename mutation then hits getColumnsForNewDataPart (MutateTask.cpp:912) with b already present and aborts:

LOGICAL_ERROR: trying to rename column a to b, but part all_1_1_1 already has column b

Root cause is exactly the asymmetry you point at: the expired-columns loop only checks columns_present_in_parts.contains(rename_from), and rename_from is not treated as stale when it is re-added (unlike a pending DROP, which AlterConversions::dropped_columns handles).

Fix: skip the keep-alive when rename_from is itself a live storage column (the re-added case). The merge then expires b as it did before the #80648 change; the rename mutation re-derives b from the physical a, and the re-added a is defaulted. That matches master's behavior for this case, and the #80648 Dynamic-no-default preservation is untouched for the pure-rename case.

Both directions, deterministic, Build-ID verified (debug):

  • master (no fix, 6DD87B5D...): reuse scenario already correct (a=default, b=old data, no crash).
  • current PR without this guard (D4A8582A...): full 04238 FAILS (server abort above).
  • with this guard (FEC5BFAE...): 04238 PASS 30/30; Dynamic-no-default phase still count=8.

Added Phase 3 to 04238_alter_rename_column_merge_race.sh (RENAME a->b pending, then ADD COLUMN a, then OPTIMIZE FINAL) that fails without the guard and passes with it.

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.

The current code still does not make the re-added a default while the RENAME COLUMN a TO b mutation is still pending.

MergeTask.cpp:728-744 now expires b in the reuse case, but the read side is unchanged:

  • MergeTreeBlockReadUtils.cpp:105-123 still maps logical b back to physical a via getColumnOldName.
  • IMergeTreeReader.cpp:370-385 will also read logical a from the same physical a if that file exists in the part.
  • AlterConversions.cpp:292-308 only treats an on-disk column as stale when it is in dropped_columns; a pending rename does not mark rename_from stale.

So for the phase-3 merged part shape (system.parts_columns = ['a'] while the rename is still pending), both logical names still resolve to the old a bytes until the rename mutation materializes. This removes the later LOGICAL_ERROR, but it does not actually deliver the “re-added a defaults” behavior claimed above.

I think the original read-side fix is still needed here: once a pending rename claims physical a for logical b, direct lookup of logical a has to treat that on-disk a as stale, the same way DROP COLUMN/re-add does.

Follow-up on the ClickHouse#80648 residual fix. The merge expired-columns check treats
a pending RENAME COLUMN old -> new target as present when a source part still
physically holds old. RENAME COLUMN is a barrier, but a later non-barrier
ADD COLUMN old does not wait for the pending rename, so metadata can carry both
old and new while the parts store only the pre-rename old. In that state the
check kept new alive off the physical old bytes, so the merged part carried both
old and new from one physical column and the pending rename mutation, finding new
already present, aborted with a LOGICAL_ERROR in getColumnsForNewDataPart.

Skip the keep-alive when the rename source is itself a live storage column
(the re-added case). The merge then expires new as before the ClickHouse#80648 fix; the
rename mutation re-derives it and the re-added old is defaulted, which is the
correct pre-fix behavior for this case. The Dynamic no-default preservation
(ClickHouse#80648) is unchanged for the pure-rename case.

Adds a third deterministic phase to 04238_alter_rename_column_merge_race.sh
that fails (server abort) without this guard and passes with it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Avogar
Avogar added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 5a45545 Jul 30, 2026
177 of 179 checks passed
@robot-clickhouse robot-clickhouse added 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 labels Jul 30, 2026
robot-ch-test-poll added a commit that referenced this pull request Jul 31, 2026
Cherry pick #109356 to 25.8: Fix data loss when a merge races ALTER RENAME COLUMN on a column without a default expression
robot-clickhouse added a commit that referenced this pull request Jul 31, 2026
…ME COLUMN on a column without a default expression
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 31, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Jul 31, 2026
…ME COLUMN on a column without a default expression
clickhouse-gh Bot added a commit that referenced this pull request Jul 31, 2026
Backport #109356 to 26.7: Fix data loss when a merge races ALTER RENAME COLUMN on a column without a default expression
alexey-milovidov added a commit that referenced this pull request Jul 31, 2026
Backport #109356 to 26.5: Fix data loss when a merge races ALTER RENAME COLUMN on a column without a default expression
alexey-milovidov added a commit that referenced this pull request Jul 31, 2026
Backport #109356 to 26.3: Fix data loss when a merge races ALTER RENAME COLUMN on a column without a default expression
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 1, 2026
…ME COLUMN on a column without a default expression
clickhouse-gh Bot added a commit that referenced this pull request Aug 1, 2026
Backport #109356 to 26.6: Fix data loss when a merge races ALTER RENAME COLUMN on a column without a default expression
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up to my design question above (issuecomment-5123880170), now that this PR is merged.

Merging it answered the fork I asked about: keeping the pending rename's target alive during the merge
is the accepted direction, so I dropped the "refuse to merge while a rename is pending" alternative and
re-planned as an extension of this PR. That ran into a cost question I also should not decide alone.

The remaining defect. A compound single-ALTER rename RENAME COLUMN a TO c, RENAME COLUMN b TO a
registers two co-pending renames. The keep-alive added here treats the target as present only when
rename_from is not a live storage column, which is the right test for a re-added source. In the
compound form the name a is live for a different reason: the second rename supplies it. So the guard
declines, c is expired, and with no default on c the old a values are gone. With a default on c
the target survives but the merged part keeps its sources' pre-rename mutation version, the rename is
re-selected for a part that already has c, and it fails permanently on the existing consistency check
in getColumnsForNewDataPart (is_done = 0, latest_fail_reason code 49; it aborts in debug and
sanitizer builds). Both faces need the same fix: the second state is the first one's post-fix state.

Recognizing the compound case in the producer is small. The problem is the consumer, which has to know
"this part already materialized this rename". I tried three ways to derive that from state the part
already carries, and all three are unsound:

  • Per-entry "target present and source absent" is vacuous here, because the co-pending rename also
    materializes and supplies a physical a, so both names are present for the entry that matters.
  • Whole-map variants fail because a live column can be legitimately absent from a part after
    ADD COLUMN with a default, or when its only values are in a patch part. Acting on absence would
    suppress a real rename and leave a column under the wrong name, which is worse than the bug.
  • No existing version carries it either: the merged part's data version is its sources', and plain
    MergeTree never advances a metadata version at all, so for the engine where this reproduces that
    value is a constant 0.

So the merge has to record what it materialized, and by this repo's own precedent a new per-part
metadata file is not additive: unknown files are checksummed unless listed in the exemption set, packed
storage enumerates its metadata files explicitly, and each of these files has its own replication
protocol version. The closest precedent, invalidated_system_columns.txt, measures 32 files. I also
have not established what such a record would mean for a replicated merge, since the replicated queue
filters each part's rename map by that part's own metadata version while the merge predicate only
equalizes data versions, so one merge can mix sources with different maps.

The question: is a per-part record plus a protocol bump acceptable for this case, or would you
rather the window itself were closed, so no merge output straddles a pending rename for the affected
parts? The second needs no format change and no protocol bump, and #112783 suggests serializing around
unfinished rename mutations is not unwelcome, but it is a different design and I have not costed it.

Happy to implement either. I am not opening a PR until the cost question is settled, since the two
answers share no code.

Repro, if useful (debug build, mt_select_parts_to_mutate_no_free_threads is the only window that
holds; SYSTEM STOP MERGES does not, for the reason documented in the test this PR added):

CREATE TABLE swap (id UInt64, a String, b String)
ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 0;
INSERT INTO swap VALUES (1,'A1','B1'),(2,'A2','B2');
INSERT INTO swap VALUES (3,'A3','B3'),(4,'A4','B4');
SYSTEM ENABLE FAILPOINT mt_select_parts_to_mutate_no_free_threads;
ALTER TABLE swap RENAME COLUMN a TO c, RENAME COLUMN b TO a SETTINGS alter_sync = 0;
OPTIMIZE TABLE swap FINAL;
SYSTEM DISABLE FAILPOINT mt_select_parts_to_mutate_no_free_threads;
SELECT id, c, a FROM swap ORDER BY id;

Expected c = A1..A4, a = B1..B4. Actual: c empty, a = B1..B4, merged part ['a','id'].

alexey-milovidov added a commit that referenced this pull request Aug 4, 2026
Backport #109356 to 25.8: Fix data loss when a merge races ALTER RENAME COLUMN on a column without a default expression
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

One more measurement for the question I asked above (issuecomment-5154420674), which I think makes the
"close the window" side cheaper than I costed it. I am not asking anything new here and I am not
opening a PR until that question is answered.

The same pending-rename window has a second face: a re-added source. The two-ALTER form no longer
reproduces since #112783, but a compound single ALTER registers one mutation and has no earlier
barrier to wait for, so it still gets there:

CREATE TABLE t (id UInt64, a String) ENGINE = MergeTree ORDER BY id
  SETTINGS min_bytes_for_wide_part = 0;
INSERT INTO t SELECT number, 'payload_' || toString(number) FROM numbers(500);
ALTER TABLE t RENAME COLUMN a TO b, ADD COLUMN a String SETTINGS alter_sync = 0;
SELECT countIf(b != ''), countIf(a != '') FROM t;   -- 500 500; `a` reads b's values

a should be empty. It is also durable, not just a wrong read: INSERT INTO cp SELECT id, b, a FROM t
in the window stores OLD_A in cp.a permanently, and WHERE a = '' returns 0 where 500 is correct.

The reason I am reporting it here rather than sending the obvious fix: I implemented the read-side
repair (ignore a part column that a pending rename has renamed away, keyed on the requested name) and
measured that it destroys b permanently whenever a merge runs in the window. With
OPTIMIZE TABLE t FINAL inside the window, countIf(b != ''), countIf(a != '') goes
500 500 -> 0 0 and stays 0 0 after the rename materializes, where unpatched gives 500 0.
Deterministic, Wide and Compact, and visible on disk: for the merged part's payload column,
column_data_uncompressed_bytes drops 9390 -> 4000 (4000 is 500 empty String offsets, so the
payload really is gone, not merely unreadable).

The mechanism is what I think is decision-relevant. The merge does not bake the rename in. It writes
the payload under the old physical name and leaves the mutation pending:

in-window merged part:  system.parts_columns -> ['id','a'],  system.mutations -> is_done = 0
after materialization:  ['id','b'],  b = payload, a = empty   (correct)

The keep-alive here deliberately declines to protect the target when rename_from is a live storage
column, so b is expired and the merge's read set is {id, a} where a is the re-added name.
Physical a is therefore the only surviving copy of b's payload, and the aliasing read is what
carries it into the merged part. So on the merge path that read is load-bearing: the correct end state
today is produced by the expiry and the aliasing cancelling out. A uniform read-side fix removes one
half of that pair, and fixing the expiry half instead does not help, because there is no physical b
to preserve, only physical a, read through the aliasing a uniform guard would have just forbidden.

Scoping the guard to query reads only would work on both axes I measured, but it gives one physical
column different meanings per subsystem, MutateTask and the projection/backup paths are on the
unguarded side and I have not measured them, and EXPLAIN WHATIF reads through
MergeTreeReaderSettings::createForMergeMutation (WhatIfEmpiricalEstimator.cpp:144), so it would
land on the opposite side from SELECT on the same table.

Affected on master and on the release builds of 26.7, 26.6, 26.5, 26.3 and 25.8. Default
alter_sync = 1 is safe; the window needs alter_sync = 0.

kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…ALTER RENAME COLUMN on a column without a default expression
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…ALTER RENAME COLUMN on a column without a default expression
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-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.

Flaky test 03040_dynamic_type_alters_2: values read back as NULL after ALTER

4 participants