Repository navigation
Fix data loss when a merge materializes a pending RENAME COLUMN - #115981
alexey-milovidov merged 15 commits into
Conversation
…sion A merge writes its result with the column names of the current metadata, so it materializes a pending `ALTER TABLE ... RENAME COLUMN` by itself. `FutureMergedMutatedPart::assign` takes the maximum data version of the source parts, so nothing records that it did: the rename mutation stays pending for the merged part. When it runs, `AlterConversions` resolves the new name back to the physical name the merge already replaced, the column reads as missing and is filled with defaults. A column with no default expression has nothing to refill from, so its values are lost for good - reads return `NULL`, and for `Dynamic` the type census collapses to `None`. Extend the merged part's mutation version through the contiguous run of pending mutations that consist only of metadata mutations, which are exactly the ones a merge materializes on its own. A part carries a single data version, so it cannot express a non-contiguous applied set; when a pending `RENAME COLUMN` sits past a mutation the merge does not materialize, refuse the merge instead of losing the data. That state is unreachable in practice, because `RENAME COLUMN` is a barrier command and `alter` waits out every earlier mutation before registering it, and `DROP COLUMN` - the other metadata mutation - is a no-op when re-applied to a part that no longer has the column. `ReplicatedMergeTree` is unaffected: it records the table metadata version in each part, and `ReplicatedMergeTreeQueue` already excludes metadata mutations a part has already seen. The failure only shows on Compact parts, where the rename mutation rewrites the whole part through the reader. In a Wide part it only renames files, which is a no-op once the merge has already written the new name. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=9f19372141ea123d170d0afd41cf99d6d6631a15&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [75a2b4c] Summary: ✅
AI ReviewSummaryThis PR teaches plain Missing context / blind spots
Final Verdict✅ No new findings from this review. LLVM Coverage ReportMeasured on commit 75a2b4c.
Changed lines: Changed C/C++ lines covered: 62/73 (84.93%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units61 translation units recompiled, 674 s compile time in total, 61 of them have a recent master baseline. |
…-merge-materialized-rename-not-recorded
…ding for a merged part `isMaterializedByMerge` looked only at `MutationCommand::type`, so `CLEAR COLUMN` - a `DROP_COLUMN` command with `clear` - and a command scoped to a single partition counted as materialized by the merge, and the merged part's data version was extended past them. Neither is lost in practice: a pending `DROP_COLUMN` is reported by `AlterConversions` as a dropped column regardless of `clear`, so the merge reads the column as missing and writes defaults - it does materialize a clear, and the mutation re-applied later is a no-op. Verified by holding the clear mutation unselected with the `mt_select_parts_to_mutate_no_free_threads` failpoint: the merged part comes out as `all_1_2_1_3` with the version extended and the values are cleared either way. Still, a merged part should record only what the merge provably materialized for it, and the equivalence above is too subtle to rely on - a partition-scoped command is not even applied to the parts of the other partitions, while the data version is per part. Exclude both, so the merge leaves those mutations pending. New test `05044_clear_column_materialized_by_merge`, for a merge that runs while a `CLEAR COLUMN` is still pending: the merged part keeps the mutation pending (`all_1_2_1`), reads return the cleared values, and they stay cleared once the mutation runs. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115981&sha=24d02c6d25c3b4427eab9471277f27d84d47f51c&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%202%2F6%29 ( It is unrelated to this pull request: the failure is |
|
Root cause: the Keeper cluster lost quorum for about 20 seconds, node1's Keeper session expired one second before the failing statement, and the test does not retry an error that is explicitly documented as retryable. Timeline from the job's
node1's own log for that minute is already rotated out of the artifact (oldest surviving line is 09:09:15), but node2 hit the identical throw at 09:07:25 with its log intact, and that occurrence is the informative one: Two things follow. The uncommitted entry is cleanly skipped by the other replica, so a retry cannot double-execute. And the refresh machinery that hit the same error did retry: the next attempt is logged as The test calls I agree it is unrelated to your change. Confirming your CIDB reading: 1 hit in 30 days. Over 90 days the test failed 39 times across 8 pull requests and 0 times on master, but at other statements and mostly with No fix is in progress. I will open a separate PR making the drops in that stress loop tolerate the retryable Code 571, and link it here. If you would rather have |
|
Following up on my analysis above. I have a root cause, but I am not opening a PR yet, because every fix I can build lands in a place only you can choose between. Details below, then three options and my recommendation. The window is narrower than I first described. The failure is not specific to the drop I pointed at. The predicate is Code 571 is overloaded, which rules out the obvious retry predicate. Three sites throw
Anything keyed on the error code would also retry "Database is not initialized or is being dropped", masking a real teardown bug. Today the only sound discriminator is the message substring The options, and why I am not picking:
Retrying is safe in all cases: the entry is created with an ephemeral My recommendation is option 1 if you want it fixed, since it is the only one that covers the stateless tests, and option 3 otherwise. I would rather not add a per-test Python retry: it re-implements the client loop one test at a time, and a blanket |
The test passed even if the merge wrongly recorded the pending `CLEAR COLUMN` as materialized, because the merge zeroes the column either way. Pin the active part name and data version before releasing the failpoint: with the fix the merged part is `all_1_2_1` with data version 1, while the broken classification produces `all_1_2_1_3` (measured on a counterfactual build). Co-Authored-By: Claude Fable 5 <[email protected]>
…use a merge `isMaterializedByMerge` rejected every command it did not recognise as a metadata mutation, whatever partition the command was scoped to. A pending `ALTER TABLE ... UPDATE ... IN PARTITION 1` leaves nothing pending for a part of partition 2 - `MutateTask` skips it through `canSkipMutationCommandForPart` and clones the untouched part forward to the mutation version - but it stopped the scan all the same, so `getMutationVersionForMergedPart` refused every merge in the other partitions as soon as a `RENAME COLUMN` was pending behind it, including `OPTIMIZE TABLE ... PARTITION 2 FINAL`. Compare the partition of the command against the partition of the result part before looking at the kind of the command, and treat a command scoped elsewhere as irrelevant for that part. A command scoped to the partition being merged is still left pending. The `alter->partition` check this replaces was in fact unreachable: only `RENAME_COLUMN` and `DROP_COLUMN` get past `AlterConversions::isSupportedMetadataMutation`, `RENAME COLUMN` has no `IN PARTITION` form, and the only partition-scoped `DROP_COLUMN` is `CLEAR COLUMN`, which the `clear` check above already rejects. An `UPDATE` never reached it. The scan now reparses the AST of every command and evaluates partition expressions, so `getMutationVersionForMergedPart` first checks that a metadata mutation is pending at all - the case the whole function exists for - and returns immediately otherwise. That is the path every merge of every table takes. Also corrected the claim that the refusal is unreachable: two `ALTER` queries cannot reach it, because `RENAME COLUMN` is a barrier command and `alter` waits out every earlier mutation before registering the rename, but a single `ALTER` that combines a rename with an `UPDATE` puts both commands into one entry, and a merge does not materialize that entry.
…adata mutation past a pending one A merge materializes every pending `RENAME COLUMN` and `DROP COLUMN` (including its `CLEAR COLUMN` form) by itself, through `AlterConversions`. The merged part carries a single data version, so once an earlier mutation is left pending the merge cannot record them - and that earlier mutation reads the column the merge already renamed or cleared. Refuse such a merge for `DROP COLUMN` as well, not only for `RENAME COLUMN`.
…-merge-materialized-rename-not-recorded
Verified on a running server: the reported loss around `CLEAR COLUMN` is not caused by the merge. `ALTER TABLE t UPDATE z = y + 100 WHERE 1, CLEAR COLUMN y` is rejected outright by `checkDropOrRenameCommandDoesntAffectInProgressMutations`, and in the variants that are accepted (`MATERIALIZE COLUMN z` with `z` defaulting to `y + 100`, followed by `CLEAR COLUMN y`) the earlier mutation reads the cleared values through `AlterConversions` even when no merge happens at all. Refusing the merge does not prevent it, so keep the barrier narrow: `DROP COLUMN` is idempotent, and re-applying it to the merged part is a no-op.
…-merge-materialized-rename-not-recorded
…mutation scan A mutation command can carry its partition scope in either `ASTAlterCommand::partition` (`IN PARTITION p`) or `ASTAlterCommand::partitions` (`IN PARTITION p1, p2, ...`). `canSkipMutationCommandForPart` honours both, so both leave nothing pending for a part outside the scope, but `isMaterializedByMerge` only looked at the first one. A pending `UPDATE ... IN PARTITION 1, 2` therefore stopped the scan for a merge in partition 3, so the merged part did not record the metadata mutations behind it - and a pending `RENAME COLUMN` behind it refused the merge outright. Extracted the scope test into `getPartitionScope` covering both shapes.
…-merge-materialized-rename-not-recorded # Conflicts: # src/Storages/StorageMergeTree.h
…COLUMN` The refusal in `getMutationVersionForMergedPart` had no test of its own. None of `05037`, `05044` or `05055` produces a pending mutation entry that a merge does not materialize with a `RENAME COLUMN` behind it, so a regression there would let a merge materialize the rename without recording it, and no test would fail. The reachable shape is a single `ALTER TABLE ... CLEAR COLUMN y, RENAME COLUMN d TO d1`: both are metadata alters, so `AlterCommands::getMutationCommands` keeps them in one entry, and `RENAME COLUMN` being a barrier command only makes `alter` wait for the mutations registered before it. New test `05076_merge_refused_before_pending_rename_column` holds that entry unselected with the `mt_select_parts_to_mutate_no_free_threads` failpoint, asserts the entry shape - one `mutation_id`, one `CLEAR COLUMN` and one `RENAME COLUMN` - and then that `OPTIMIZE ... FINAL` fails with `CANNOT_ASSIGN_OPTIMIZE` while both source parts stay active. Once the entry has run, the same `OPTIMIZE` merges them and the values of the renamed `Dynamic` column are all there. The other shape suggested in review, `MATERIALIZE COLUMN x, RENAME COLUMN d TO d1`, does not reach it: `MATERIALIZE COLUMN` is not an `AlterCommand`, only `MutationCommand::parse` accepts it, so `InterpreterAlterQuery` puts it in a segment of its own that registers first and the barrier rename then waits for it. Verified on a running server: with mutation selection blocked, only `(MATERIALIZE COLUMN m)` is registered and the `ALTER` never returns.
`05044` and `05055` assert the name of the part that their `OPTIMIZE ... FINAL` produces, which is what distinguishes a recorded mutation version from a pending one. A background merge that wins the race produces the same name, but then `OPTIMIZE ... FINAL` rewrites the single result part and its level goes up by one, so the assertion would read `all_1_2_2` or `3_3_4_2_6` instead. Create those tables with `max_bytes_to_merge_at_max_space_in_pool = 1`, which stops background merges while `OPTIMIZE ... FINAL` ignores the limit, as the new `05076` does. The references are unchanged.
Closes: #111001
Related: #109356
Related: #80648
A merge writes its result with the column names of the current metadata, so it materializes a pending
ALTER TABLE ... RENAME COLUMNby itself.FutureMergedMutatedPart::assigntakes the maximum data version of the source parts, so nothing records that it did: the rename mutation stays pending for the merged part. When it runs,AlterConversionsresolves the new name back to the physical name the merge already replaced, the column reads as missing and is filled with defaults. A column with no default expression has nothing to refill from, so its values are lost for good.This is a wrong-results bug in plain
MergeTree, not flakiness. It surfaces as03040_dynamic_type_alters_2_compact_merge_treefailing onmasterand on unrelated pull requests - 15 hits in the CI database over the last 30 days, two of them onmasteritself.Dynamicis not special; it just makes the loss unavoidable, since it cannot carry a default expression.From the server log of the reported run (database
test_u5o3o5i6h9c1):It is not the mechanism fixed in #109356. That one dropped the column from the merged part through
expired_columns; here the column is kept and the loss is in name binding on the second application.The fix
Extend the merged part's mutation version through the contiguous run of pending mutations that consist only of metadata mutations, which are exactly the ones a merge materializes on its own. The merge above now produces
all_1_5_1_6, and the rename mutation is no longer pending for it.A part carries a single data version, so it cannot express a non-contiguous applied set. When a pending
RENAME COLUMNsits past a mutation the merge leaves pending for the merged part, the merge is refused instead of losing the data, and it becomes possible again as soon as that earlier mutation has run.Two
ALTERqueries do not reach that state:RENAME COLUMNis a barrier command, soalterwaits out every already registered mutation before registering the rename, and a permanently failing earlier mutation does not open the window either, becausecheckMutationStatusthen throws and the rename is never registered. What does reach it is a singleALTERthat combines the rename with a metadata command the merge does not materialize,ALTER TABLE ... CLEAR COLUMN y, RENAME COLUMN d TO d1: both are metadata alters, soAlterCommands::getMutationCommandskeeps them in one entry, and the barrier only makesalterwait for the mutations registered before it. A rename combined with anUPDATEdoes not -InterpreterAlterQuerysplits those into two segments, and the rename segment still waits out the update - so for that shape only the race window between the wait and the registration remains.The scope of a command is taken into account: a pending command scoped to another partition is never applied to the merged part -
canSkipMutationCommandForPartskips it and the untouched part is cloned forward to the mutation version - so it does not refuse the merge, and the merged part records the whole entry. Only a command that has something left to do for that part does. Without this, anALTER TABLE ... UPDATE ... IN PARTITION 1pending behind aRENAME COLUMNwould block every merge in the other partitions, includingOPTIMIZE TABLE ... PARTITION 2 FINAL.The scope of a command is read from both shapes the parser produces,
IN PARTITION pandIN PARTITION p1, p2, ..., which are two different fields of the parsed command.ReplicatedMergeTreeis unaffected and unchanged: it records the table metadata version in each part, andReplicatedMergeTreeQueuealready excludes metadata mutations a part has already seen. This is the same model, applied to the engine that has no table-level metadata version.Testing
New test
05037_rename_column_materialized_by_merge, which uses themt_select_parts_to_mutate_no_free_threadsfailpoint to hold the rename mutation unselected while the merge runs. Without the fix it reproduces the CI signature exactly - the type census collapses to9 Noneand every concrete value reads back as\N; with the fix it passes.05044_clear_column_materialized_by_mergepins the complementary case: a pendingCLEAR COLUMNmust stay pending for the merged part.05055_merge_past_multi_partition_updatepins the partition scoping: a pendingUPDATE ... IN PARTITION 1, 2must not stop the scan for a merge in partition 3, so the merged part still records theDROP COLUMNbehind it.05076_merge_refused_before_pending_rename_columnpins the refusal itself, which the three tests above never drive: a singleALTER TABLE ... CLEAR COLUMN y, RENAME COLUMN d TO d1held unselected by the failpoint, andOPTIMIZE ... FINALthen has to fail withCANNOT_ASSIGN_OPTIMIZEand leave both source parts active. Once the entry has run, the sameOPTIMIZEmerges them and the values of the renamedDynamiccolumn are all there.The three tests that assert a part name create their table with
max_bytes_to_merge_at_max_space_in_pool = 1, so the name is the result of their ownOPTIMIZE ... FINAL- which ignores that limit - and not of a background merge that wins the race and then gets rewritten by theOPTIMIZE, one level higher.The test uses Compact parts on purpose: there the rename mutation rewrites the whole part through the reader, so a rename applied twice reads the column as missing. In a Wide part it only renames files, which is a no-op once the merge has already written the new name - which is why only the
_2_compactvariant has ever failed in CI.CI report the fix was derived from: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=9f19372141ea123d170d0afd41cf99d6d6631a15&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed data loss in
MergeTreewhen a merge runs while anALTER TABLE ... RENAME COLUMNis still pending. The merge applied the rename but did not record it, so the mutation applied it a second time and read the renamed column as missing, filling it with defaults. Columns without a default expression, such asDynamic, lost their values.Workflow [PR]
Sync PR [sync-upstream/pr/115981]
Version info
26.9.1.749(included in26.9and later)