Skip to content

Reset the level and mutation version of an adopted part on ATTACH PART/PARTITION and restore - #109686

Open
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:fix-109674-attach-part-level-reset
Open

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:fix-109674-attach-part-level-reset

Conversation

@groeneai

@groeneai groeneai commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #109674
Closes: #122940

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 SELECT ... FINAL silently returning duplicate rows after ALTER TABLE ... ATTACH PART/ATTACH PARTITION, SYSTEM RESTORE REPLICA or a restore from backup adopted a merged part with duplicate sorting keys into a ReplacingMergeTree, SummingMergeTree, AggregatingMergeTree or another FINAL-relying engine. A part attached from detached/ no longer carries the source table's merge level, a restored part keeps it only when RESTORE has checked that the table definition matches the backup, and a restored part no longer carries its mutation version, which had made the destination skip its own mutations on the adopted rows.

Description

A part in detached/ or in a backup comes from another table, so its level and mutation version describe that table. Two FINAL consumers read a non-zero level as "ORDER BY keys already collapsed": PartsSplitter skips the collapsing transform, and ReadFromMergeTree's do_not_merge_across_partitions_select_final path skips post-processing entirely with one part per partition. Since 20e5dfc789f the ATTACH sites clamped an adopted level to 1, the value both consumers trust, so duplicates survived and queries silently returned wrong results.

ATTACH PART/PARTITION now resets the level, in fillNewPartNameAndResetLevel and, for replicated tables and SYSTEM RESTORE REPLICA, in attachPartitionImpl. RESTORE resets it in restorePartsFromBackup unless the table definition was compared with the backup and matched, so a same-definition restore keeps the FINAL fast path. allow_different_table_def, a predefined table, the inner table of a materialized view and every GraphiteMergeTree (its rollup rules come from the server config) are reset. Every reset also clears the legacy-max-level flag that tryParsePartName sets for a level field of 4294967295.

The restore site also kept the source's mutation version, and getDataVersion() prefers it over the freshly allocated block number, so the destination skipped its own later mutations on the adopted rows: 6 rows where 4 are correct, on a plain MergeTree too. That reset is unconditional, because a mutation version describes table identity, which no definition establishes.

The trade on ATTACH: a lone part is never chosen for a background merge, so an attached level-0 part keeps the slower FINAL path until an explicit OPTIMIZE ... FINAL. A detached/ directory carries no definition to check.

Level after adoption for a source part with level > 0, and test coverage
entry point plain MergeTree other engines master, other engines
ATTACH PART/PARTITION, SYSTEM RESTORE REPLICA 0 0 1
restore, definition matched kept kept (GraphiteMergeTree: 0) kept, replicated 1
restore, definition not checked kept 0 kept, replicated 1

The mutation version is 0 everywhere. A replicated restore now keeps a plain MergeTree level like the non-replicated one (master: 0); it has no FINAL meaning there. A part the old ATTACH already left at level 1 keeps it through a same-definition restore, so the copy reads as the source does (as on master); OPTIMIZE ... FINAL repairs it. The cross-table clone path getLevelForAdoptedPart is untouched: it has its own hasSameMergeSemantics check.

tests/integration/test_attach_foreign_part_level_reset covers ATTACH into the three engines plus ReplicatedReplacingMergeTree and a legacy-max-level part name; no supported statement stages a foreign part in detached/. 04402_restore_foreign_part_level_reset_final covers a non-replicated restore with allow_different_table_def, 05345_restore_part_level_same_definition the same-definition restores (both engines), a replicated one with allow_different_table_def and GraphiteMergeTree. 03283_optimize_on_insert_level pinned the old level-1 part names, so its reference is updated.


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

…ry engines

A part attached from detached/ (ALTER TABLE ... ATTACH PART/PARTITION, FETCH
PART, or restore from backup) has unknown provenance. Since commit 20e5dfc
the ATTACH path kept such a part's merge level clamped to 1 for non-Ordinary
engines. But a level > 0 does not guarantee unique/collapsed ORDER BY keys when
the part was merged elsewhere (e.g. a plain MergeTree, which does not collapse
rows on merge). SELECT ... FINAL, OPTIMIZE ... FINAL and the PartsSplitter FINAL
optimization treat a lone level > 0 part as already merged and skip the
row-collapsing transform, so duplicate keys survived FINAL on
Replacing/Summing/Aggregating/VersionedCollapsing/Graphite/Coalescing engines,
returning wrong results silently.

Reset the adopted part's level to 0 at both part-adoption sites
(StorageMergeTree::fillNewPartNameAndResetLevel and
ReplicatedMergeTreeSink::writeExistingPart) so the destination re-merges the
part under its own semantics. This restores the pre-20e5dfc behavior for these
paths. The cross-table adoption path (getLevelForAdoptedPart) is unaffected: it
already has a hasSameMergeSemantics check and its own level logic.

Test 03283_optimize_on_insert_level asserted the old level-1 outcome after a
same-table DETACH/ATTACH round-trip; that assertion encoded the bug, so its
reference is updated to level 0.

Closes: ClickHouse#109674

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

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Build a lone level-1 part with duplicate keys in a plain MergeTree (OPTIMIZE FINAL), copy its dir into a ReplacingMergeTree's detached/, ATTACH PART, then SELECT count() FINAL. Returns 6 (buggy) vs 3 (correct) every time. New test 04401_attach_foreign_part_level_reset_final automates it for Replacing/Summing/Aggregating.
b Root cause explained? An adopted part keeps its source merge level. Since 20e5dfc789f the ATTACH path clamps that level to 1 (not 0) for non-Ordinary engines. A lone level>0 part is treated by FINAL and PartsSplitter as already merged, so the row-collapsing transform is skipped. A plain-MergeTree part at level>0 still holds duplicate ORDER BY keys, so FINAL returns them.
c Fix matches root cause? Yes. Reset the adopted part's level to 0 at both adoption sites (fillNewPartNameAndResetLevel, writeExistingPart) so the destination re-merges under its own semantics. This targets the exact level>0 assumption that is violated, restoring pre-20e5dfc behavior for these paths.
d Test intent preserved / new tests added? New test 04401 added (3 engines). 03283_optimize_on_insert_level's reference asserted the old level-1 outcome after a same-table DETACH/ATTACH round-trip; that assertion encoded the bug, so the reference is updated to level 0 (the correct, safe outcome). The test still verifies the ATTACH level behavior, now correctly.
e Both directions demonstrated? Yes. On a debug build: buggy binary (Build ID 7ba54e95) -> attached level 1, FINAL=6; fixed binary (0cad001f) -> attached level 0, FINAL=3. 04401 passes on the fixed build; 03283 MergeTree section matches the new reference byte-for-byte.
f Fix is general across code paths? Yes. Both part-adoption-from-detached sites are fixed: StorageMergeTree::fillNewPartNameAndResetLevel (ATTACH PART/PARTITION) and ReplicatedMergeTreeSink::writeExistingPart (replicated ATTACH + restore-from-backup). The reset-to-0 is engine-agnostic, so it also covers VersionedCollapsing/Graphite/Coalescing, not just Replacing/Summing/Aggregating. The cross-table path (getLevelForAdoptedPart) is intentionally left alone: it has its own hasSameMergeSemantics uniqueness check.
g Fix generalizes across inputs? Yes. The reset does not depend on datatypes or part shape; it applies to any adopted part regardless of engine, column types, or wide/compact format. Verified across Replacing/Summing/Aggregating in 04401.
h Backward compatible? Yes, and it restores the safe pre-20e5dfc behavior. No setting default, on-disk/wire format, or replication metadata change. The only behavior change is a lone attached part re-merges once (correctness win); no downgrade path needed.
i Invariants and contracts preserved? Yes. Upholds the PartsSplitter/FINAL invariant that a lone level>0 part has unique/collapsed keys (previously violated for foreign parts). part->info.level is set before getNewName, mutation reset unchanged, all under the parts lock. No block-structure or ordering invariant is touched.

Session id: cron:clickhouse-worker-slot-4:20260707-163700

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @alesapin — could you review? This resets the adopted part level to 0 on ATTACH PART/PARTITION for non-Ordinary engines. @CurtizJ, this touches the level clamp you added in 20e5dfc (fillNewPartNameAndResetLevel): for a foreign part from detached/, level>0 does not imply unique keys, so FINAL silently returned duplicates. 03283's reference is updated accordingly.

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.

use cp -rl instead

-l Create hard links to regular files in a hierarchy instead of copying.

Hard-link the foreign part into detached/ instead of a plain recursive
copy. The test only ATTACHes and reads the copy, never mutates it, so
sharing inodes is safe and faster.

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

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Done in e377db8. Switched to cp -rl. The test only ATTACHes and reads the copied part, never mutates it, so sharing inodes is safe. Verified locally: attached part level 0, SELECT count() FINAL = 3.

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6aa713d]

Summary: ✅


AI Review

Summary

This PR fixes the two foreign-provenance bits that made adopted parts unsafe to trust: level is now reset on ATTACH/unchecked restore paths where the destination cannot assume matching merge semantics, while same-definition restores keep level when that invariant was actually verified; mutation is reset on restore so the destination never skips its own later mutations. I reviewed the current diff plus the existing discussion threads, traced the non-replicated, replicated, and SYSTEM RESTORE REPLICA adoption paths, and I do not see a remaining correctness hole in the changed surfaces.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 27, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 27, 2026
groeneai and others added 2 commits August 27, 2026 22:49
The stateless test staged a data part of a foreign table into another table's
detached/ directory. The stateless suite runs against arbitrary server
configurations (object storage, shared MergeTree, encrypted disks) where the
local part layout either does not exist or does not mean what the test assumes,
so functional tests must not fabricate or manually intervene with data parts,
and the scenario cannot be expressed without doing exactly that: no supported
statement puts a part of a foreign table into detached/. An integration test
owns its server and disk configuration, which makes that assumption explicit.

tests/integration/test_attach_foreign_part_level_reset keeps the assertions that
carry the fix, adopted part level 0 and a deduplicated SELECT count() FROM t
FINAL, for ReplacingMergeTree, SummingMergeTree and AggregatingMergeTree. It
adds a ReplicatedReplacingMergeTree case that reaches the second adoption site,
ReplicatedMergeTreeSink::writeExistingPart, against a real Keeper, which the
stateless test could not do. It keeps the hard links asked for in review of the
original test and now also asserts that the still-live source part is unchanged
afterwards, so sharing inodes is shown to be safe rather than argued.

Measured both directions on a debug build: with the fix all four cases pass;
with the two level resets reverted all four observe level 1 and SELECT count()
FROM dst FINAL returns 6 instead of 3.

The 03283_optimize_on_insert_level reference update is unchanged: that test uses
only supported statements.

Co-Authored-By: Claude Opus 5 <[email protected]>
Both blocks had grown to five and six lines restating the defect, the FINAL and
PartsSplitter code paths involved and the issue number. That belongs in this
history, not at the call site: a reader of the line needs only the property that
is not visible from the code, which is that the level of an adopted part says
nothing about whether its ORDER BY keys are collapsed.

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

Copy link
Copy Markdown
Collaborator Author

Style check flagged the regression test I added here: staging a part of a foreign table into another table's detached/ writes the server's data on disk, which stateless tests must not do. That check is new on master and this test predates it, so it only surfaced when CI first ran on this branch today.

The test is now tests/integration/test_attach_foreign_part_level_reset. It keeps the same assertions (adopted part level 0, and SELECT count() FROM t FINAL deduplicated) for ReplacingMergeTree, SummingMergeTree and AggregatingMergeTree, keeps the hard links @ den-crane asked for, and adds a ReplicatedReplacingMergeTree case so the second adoption site, ReplicatedMergeTreeSink::writeExistingPart, is covered against a real Keeper. Measured both ways on a debug build: 4/4 pass with the fix, 4/4 fail with the two level resets reverted (level 1, and count() FINAL 6 instead of 3).

That also closes something I flagged earlier on this PR as untested locally: the replicated half of 03283_optimize_on_insert_level had never been run, since I could not bring up a Keeper replica at the time. Replaying that test's own SQL for both halves against a real Keeper now reproduces the updated reference byte for byte.

The source fix is unchanged. The only other edit is shortening the two comments at the level-reset sites, which had grown into a restatement of the defect.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
RESTORE TABLE <t> AS <existing table> SETTINGS allow_different_table_def = 1
skips the table definition check, so a backup taken from a plain MergeTree can
be restored into a ReplacingMergeTree/SummingMergeTree/AggregatingMergeTree.
StorageMergeTree::attachRestoredParts keeps the level such a part carries, and
FINAL reads a lone level > 0 part directly instead of collapsing it, so the
duplicate ORDER BY keys survive.

Measured on a plain MergeTree part merged to level 1 with 6 rows and 3 distinct
keys, restored into a ReplacingMergeTree: level stayed 1 and
SELECT count() FROM t FINAL returned 6 instead of 3.

The level is only discarded for engines that collapse rows during a merge.
For Ordinary MergeTree no merge semantics depend on it, so nothing changes
there; the new test pins both directions.

The replicated twin was already covered, because
StorageReplicatedMergeTree::attachRestoredParts routes parts through
ReplicatedMergeTreeSink::writeExistingPart.

Reported by clickhouse-gh[bot] on ClickHouse#109686.
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 6aa713deec34d7ed83343c8f903247d7e317226e was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
groeneai and others added 4 commits August 28, 2026 05:17
attachRestoredParts renamed the part but left info.mutation alone, and
getDataVersion() returns the mutation version when it is set rather than the
freshly allocated block number. Mutation versions are numbered per table, so a
part restored from another table placed itself at that table's version. Both
selectPartsToMutate and getOnFlyMutationCommandsForPart start from
current_mutations_by_version.upper_bound(getDataVersion()), so every mutation
the destination issued at or below the carried-over version was skipped on the
restored rows, silently and without any error.

Measured before this change: a part of a plain MergeTree carrying _7, restored
into a ReplacingMergeTree via allow_different_table_def, kept data_version 7,
and a following ALTER TABLE ... DELETE (version 3) left all six rows in place
while correctly deleting from a natively written part in the same table under
the same mutation.

The two other adoption sites already discard the version:
fillNewPartNameAndResetLevel for ATTACH PART, and replacePartitionFrom by
building fresh part info. ReplicatedMergeTreeSink::writeExistingPart does too,
which is what the replicated implementation of this same virtual method calls,
so the non-replicated path was the only one that carried it over. The reset is
unconditional for the same reason: nothing about it depends on merge semantics.

The block number allocator is seeded from getMaxBlockNumber(), which maxes in
info.mutation, and from the largest loaded mutation version, so the new block
number is above every mutation the destination knows about. Mutations issued
before the restore stay inapplicable to the newly added rows and later ones
apply.

Co-Authored-By: Claude Opus 5 <[email protected]>
The branch base predates the invalidated-system-columns mechanism that the
adoption paths this PR touches now rely on, so the change can only be validated
against a tree that carries it.

Co-Authored-By: Claude Opus 5 <[email protected]>
tryParsePartName records a level field of 4294967295 as level = MAX_LEVEL plus
use_legacy_max_level = true so the name can be serialized back unchanged
(MergeTreePartInfo.cpp:136-146), and both getPartNameV1 and getPartNameV0 obey
that flag under chassert(level == MAX_LEVEL). The three adoption sites forced the
level and left the flag set, so a part staged in detached/ or carried in a backup
under such a name aborted a debug or sanitizer build inside
IMergeTreeDataPart::getNewName, and in a release build was written back as
..._4294967295 while holding level 0 in memory. After the next reload that name
parses as MAX_LEVEL again, which PartsSplitter and ReadFromMergeTree read as
already collapsed, so this PR's own contract was silently undone for that part.

Master aborts the same way at both ATTACH sites, for a plain MergeTree
destination too, so that half is pre-existing. At attachRestoredParts master
leaves the level alone and the name round-trips, so there the abort is new with
the level reset. The clear is placed inside the reset_level branch: an Ordinary
restore keeps the level and must keep the flag with it, or its part would be
renamed from ..._4294967295 to ..._999999999 for no reason.

test_attach_foreign_part_level_reset gains an arm that attaches a part staged
under the legacy name; through the existing parametrization that arm covers both
fillNewPartNameAndResetLevel and ReplicatedMergeTreeSink::writeExistingPart. The
restore site gets no arm, because its only carrier is a backup whose part
directory and .backup manifest have been renamed by hand, and staging one needs a
backups disk the shared test instance does not declare.

That test's hard-link assertion now reads CHECK TABLE src instead of comparing
hash_of_all_files. CHECK TABLE was chosen over a DETACH/ATTACH reload because
hash_of_all_files is computed from part->checksums, which on load are read back
from checksums.txt rather than recomputed from the data files, so a byte flipped
inside data.bin survives a reload with the same value. With one byte flipped in
the inode shared with the staged copy, the new assertion fails and the old one
passes.

Co-Authored-By: Claude Opus 5 <[email protected]>
Two arms of test_attach_foreign_part_level_reset held whatever the adoption
sites did, so they passed with the level reset removed. No source file changes
here; both are test defects.

The closing OPTIMIZE TABLE dst FINAL collapsed the part whatever its level.
optimize_skip_merged_partitions defaults to false (Settings.cpp:5765) and its
own documentation says a plain OPTIMIZE ... FINAL "rewrites the one part even if
there is only a single part" (:5770), so the row count fell to the distinct-key
count either way. The skip is conditional exactly on the level this change
controls: with final, the setting on, one part in the partition and no TTL
declared, selectPartsToMerge returns NOTHING_TO_MERGE for level > 0 and merges
otherwise (MergeTreeDataMergerMutator.cpp:375-386). The arm now pins the setting
and runs while dst still holds exactly one attached part, which also pins the
user-visible half of the trade this PR makes. With master's level cap restored at
both ATTACH sites it fails 'assert 6 == 3' on each of the four parametrizations
run separately, one fresh cluster each.

The legacy-name arm was blind on the replicated parametrization. It staged a
second hard-linked copy of the same source part into the dst that already held
that part, and attachPartition passes deduplicate_part = true
(StorageReplicatedMergeTree.cpp:7495) while deduplicate is
replicated_deduplication_window != 0 (ReplicatedMergeTreeSink.cpp:132-138),
default 10000. The hash is built from the part's own checksums and partition id
(:646), which a hard link reproduces exactly, so the second attach conflicted,
the part was renamed back into detached/ (:653-666) and the query still reported
success. Measured on that arm: one active part rather than the two the
non-replicated arms get, and part_log recording the attach with error 389,
INSERT_WAS_DEDUPLICATED. The assertion counting active parts with a non-zero
level or a legacy name therefore read a vacuous zero there. The legacy
attachment now gets a freshly created dst, so nothing can collide with it, and
asserts through active_part, which requires exactly one row and so fails on an
empty table instead of reading zero.

Both halves of the legacy clear are now pinned per arm. Dropping
use_legacy_max_level = false from ReplicatedMergeTreeSink::writeExistingPart
alone fails only replicated_replacing and leaves the other three passing;
dropping it from fillNewPartNameAndResetLevel alone fails exactly those three
and leaves replicated_replacing passing. Each abort is
chassert(level == MAX_LEVEL) in getPartNameV1 (MergeTreePartInfo.cpp:222),
reached from the mutated site, on the query attaching the part named
all_1_2_4294967295. In a release build, where that assertion is compiled out,
the name assertion is what covers the same state.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai changed the title Reset adopted part level to 0 on ATTACH PART/PARTITION for non-Ordinary engines Reset the level and mutation version of an adopted part on ATTACH PART/PARTITION and restore Aug 28, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review of this change

I run every change past an independent cold review plus a second model before pushing. Verdicts
below; nothing here needs action from a reviewer.

# Finding Verdict
❌ use_legacy_max_level was left set while the adopted part's level was forced to 0. A part whose name carries the pre-21.6 max level 4294967295 parses to MAX_LEVEL with that compatibility flag, and getPartNameV1 then re-serializes 4294967295 whatever level it holds, so the reset was undone at the next reload (and tripped a chassert in debug builds). Cleared at all three adoption sites; the cross-table clone paths build a fresh MergeTreePartInfo whose flag defaults to false, so they need nothing. Fixed in c27f905
❌ The regression test's closing OPTIMIZE TABLE ... FINAL could not fail: optimize_skip_merged_partitions defaults to 0, and at that default OPTIMIZE ... FINAL rewrites a lone part whatever its level. Pinned to 1 on a single adopted part, where the outcome is a pure function of the level. Fixed in b3d0089
❌ The legacy-max-level arm was blind on the ReplicatedReplacingMergeTree parametrization: it staged a clone of the part already attached to that table, and replicated ATTACH deduplicates on the part checksum, so the second attach went back to detached/ and the assertion read zero either way. It now attaches into a fresh destination through a single-active-part oracle. Verified with one mutant per adoption site, each reddening only the arms that reach it. Fixed in b3d0089
⚠️ With part_minmax_index_columns = 'with_block_number_offset', a filter on the destination's _block_number can prune an adopted part until the table is reloaded: the min-max index is built while the part still holds the source's block number and caches it, while the reader reports the destination's. That is master's behaviour with or without this change - the synthesis follows the invalidation flag, not the level - and I measure it identical in both arms. Pre-existing, not blocking
⚠️ The use_legacy_max_level clear inside attachRestoredParts ships without a test arm. Both directions are measured (without it RESTORE aborts at MergeTreePartInfo.cpp:222), but reaching that state needs a real data part whose level field is 4294967295, which ClickHouse only ever writes for virtual DROP_RANGE entries, so an arm would pin the versioned .backup manifest format instead. The clear stays, by symmetry with the two tested sites. Correct, not blocking
💡 Two test comments say a background merge would collapse the lone attached part on its own. It cannot: merge selection refuses a one-part range (MergeTreeDataMergerMutator.cpp:366-371), as does the min_age_to_force_merge_seconds path. The SYSTEM STOP MERGES calls stay useful as state pinning, and in the restore test they are load-bearing for the reason it states correctly further down (keeping the later mutation on the on-the-fly path). Comments only; the description states the merge behaviour correctly. Correct, not blocking
💡 04402's comment on the plain-MergeTree arm reads as if every Ordinary-engine restore preserved the level. Only the non-replicated one does; a replicated restore goes through writeExistingPart, which resets for every engine, as master already did. The table above gives the two rows separately. Correct, not blocking
💡 An assertion meant to prove that hard-linking the source part into detached/ does not rewrite it compared a value cached in memory, so it could not have failed. Replaced with CHECK TABLE, checked against a deliberately corrupted staged copy. Fixed in c27f905

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, four of them, all on demand. tests/integration/test_attach_foreign_part_level_reset fails without the fix. 04402_restore_foreign_part_level_reset_final fails deterministically on 4 reference lines. A scratch probe restores a part carrying _9 into a plain MergeTree and shows the destination's own later DELETE leaving 2 rows behind. Staging a part in detached/ under a name whose level field is 4294967295 and attaching it aborts a debug server on chassert(level == MAX_LEVEL), and so does restoring a backup whose part carries that name.
b Root cause explained? A part in detached/ or in a backup earned its level and its mutation version in a different table. Two FINAL consumers read a non-zero level as "ORDER BY keys already collapsed": PartsSplitter, which skips the collapsing transform, and ReadFromMergeTree's do_not_merge_across_partitions_select_final path, which with one part per partition skips post-processing entirely. Since 20e5dfc789f the ATTACH sites clamped an adopted level to 1, exactly the value both consumers trust. Separately, getDataVersion() prefers a carried-over mutation version over the freshly allocated block number, so upper_bound(getDataVersion()) skipped the destination's own mutations on the adopted rows. Third, tryParsePartName records a level field of 4294967295 as MAX_LEVEL plus a use_legacy_max_level flag that both serializers obey, so forcing the level without clearing the flag writes the legacy value back.
c Fix matches root cause? Yes, at the producers. The three adoption sites stop handing out provenance bits they did not earn, and clear the legacy-level flag alongside the level they force; the two consumers and the serializers are untouched, because level >= 1 => keys collapsed in THIS table is a sound invariant and only its producers were wrong. No guard at a crash site, no widened bound, no weakened assertion.
d Test intent preserved / new tests added? Yes. Two new tests (a 4-arm integration test covering Replacing/Summing/Aggregating/ReplicatedReplacing, and a stateless .sh covering the restore path with a plain MergeTree negative arm), plus an arm attaching a part staged under the legacy-max-level name into a freshly created destination, so it reaches both ATTACH sites through the existing parametrization instead of being deduplicated away on the replicated one. Every shipped arm is mutation-tested rather than assumed live. The integration test's hard-link assertion moved from hash_of_all_files, which is computed from in-memory checksums and cannot observe an in-place rewrite, to CHECK TABLE src, which re-reads the files: with one byte flipped in the shared inode the new assertion fails and the old one passes. 03283_optimize_on_insert_level pinned the old level-1 part names, so only those 4 reference lines change; both its halves, including the replicated one, run and pass.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Fix a09aaf32afab7b50ba5a524d5a57374261286324: integration 4/4 PASS, 04402 OK, 03283 OK. Dropping the flag clear at one site at a time, each arm in its own fresh cluster, reddens disjoint arms: from ReplicatedMergeTreeSink::writeExistingPart only (cca7c1be14f4ea77059b5da8ba243b48f2fdab03) just replicated_replacing fails, Logical error: 'level == MAX_LEVEL' on ATTACH PART 'all_1_2_4294967295' at MergeTreePartInfo.cpp:222; from fillNewPartNameAndResetLevel only (ccc533ce1d0ae2e8ee860cd64835695526c413cb) exactly the other three fail, same assertion. Restoring master's level cap at both ATTACH sites (26517b094fc4fdc178e53d77f87d92d6899fb2c0) fails the closing OPTIMIZE ... FINAL arm assert '6' == '3' on all four. Master fa6db7a45a97464891bddefdacf3e987cf5c0599 aborts identically for both a ReplacingMergeTree and a plain MergeTree destination, so that half is pre-existing; the restore site aborts only once the level is reset, so that half is new here, shown against an assignment-only mutant 53c71036f4fc5b658892e8e46ab941aa84decb2f. Randomized stability: 04402 and 03283 at --test-runs 50 = 100/100 OK.
f Fix is general across code paths? Yes. Seventeen invariant carriers of "an adopted part carries no provenance bits" were enumerated from a repo-wide git grep "info\.level" and each disposed with a citation or a measurement. All three adoption sites are fixed; StorageReplicatedMergeTree::attachRestoredParts forces nothing itself and reaches writeExistingPart, so there is no fourth site. Of the remaining MergeTreePartInfo level assignments, one is the parser, one assigns every field of a fresh info, and one copies a drop_range built in code with MAX_LEVEL; the two that do copy a parsed info are pre-existing statements this change does not touch. The cross-table clone path getLevelForAdoptedPart is deliberately untouched: it has its own hasSameMergeSemantics check.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Engine matrix: Replacing, Summing, Aggregating, ReplicatedReplacing, plus plain MergeTree as the negative arm on the ATTACH paths and as a positive arm for the mutation half. Entry points: ATTACH PART, ATTACH PARTITION, SYSTEM RESTORE REPLICA, non-replicated and replicated backup restore. (FETCH PART only stages into detached/, so it is not one.) Level field values: ordinary levels and the legacy 4294967295 spelling, on both an Ordinary and a non-Ordinary destination. Patch parts are unaffected: nothing under PatchParts/ reads a level (0 hits, against 14 getDataVersion() hits as the discriminating control), and 03100_lwu_22_detach_attach_patches gives identical results on both arms. Adjacent settings: the _block_number/_block_offset min-max behaviour was measured across a 2x2 of arms and is identical with and without this change.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default, no serialization change, so no SettingsChangesHistory.cpp entry. Adopted parts get a _0 level suffix instead of _1, which is the pre-20e5dfc789f naming; part names are not a compatibility surface. Clearing use_legacy_max_level only affects a part whose level is being forced away from MAX_LEVEL anyway, so no name that previously round-tripped changes. The one behaviour cost is stated in the PR body rather than hidden: a lone level-0 part is never background-merged, so a restored part keeps the slower FINAL path and loses optimize_skip_merged_partitions until an explicit OPTIMIZE ... FINAL.
i Invariants and contracts preserved? Yes. All writes happen under lockParts() on the same path that already assigns the part's identity, before renameTempPartAndAdd, so no new lock, ordering or lifetime obligation appears. The serializers' level == MAX_LEVEL precondition is now satisfied rather than bypassed, and the clear sits inside if (reset_level) so an Ordinary restore keeps both its level and its name. MergeTreePartInfo::contains cannot be affected: an adopted part receives a fresh single block number above every existing block number and every mutation version, so it covers nothing and nothing covers it, at level 0 and 1 alike. Mutation ordering was measured in both directions: a mutation issued before the restore is not re-applied to the adopted rows, and one issued after it is.

Session id: cron:clickhouse-impl-slot-5:20260828-122300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @tavplubix, could you review this? A part adopted from detached/ or from a backup kept the source table's merge level, and both PartsSplitter and the do_not_merge_across_partitions_select_final path read a non-zero level as "sorting keys already collapsed", so SELECT ... FINAL silently returned duplicates. It resets the level and the carried-over mutation version at the three adoption sites, which removes the clamp added in 20e5dfc789f and updates the four 03283_optimize_on_insert_level reference lines that pinned it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b3d0089

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

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan) / Segmentation fault (STID 3773-4073) stack exhaustion from unbounded recursion in analyzer set collection, trunk defect, not caused by this PR #116978 (ours, open)
CH Inc sync still pending CH Inc sync (private, not actionable by me)

Not caused by this PR. The diff is ATTACH PART / ATTACH PARTITION part-level and mutation-version
reset in MergeTree plus its tests, with no overlap with src/Planner/ or src/Analyzer/.

Attribution read off the frames rather than the signature: of the visible trace, CollectSets.cpp:55
and CollectSets.cpp:173 each appear 10 times and InDepthQueryTreeVisitor.h:152 10 times with
:154, :204 and :212 21 times each, with zero executeQuery frames reached before the trace cap
and no sanitizer report. That is the collectSets <-> CollectSetsVisitor::enterImpl cycle, which
re-enters on a constant node's source expression, and it is the defect #116978 fixes by flattening
that dimension into a worklist. #116978 reproduces it on the official 26.8 release build (SIGSEGV
from a chain of 3500, all settings default).

Same-tree negative control: Stress test (arm_asan_ubsan, s3) passed on this exact commit at
21:40:15Z, so the abort is state and timing dependent rather than tree dependent.

Session id: cron:our-pr-ci-monitor:20260828-233000

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@filimonov

Copy link
Copy Markdown
Contributor

Similar #122940

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, this PR fixes #122940: the restore site, StorageMergeTree::attachRestoredParts, now resets the mutation version. Your script from the issue on this PR's head b3d0089 gives all_1_1_0 with data_version 1, UPDATE v = 100 sets all three rows to 100, and after the extra insert UPDATE v = 200 reaches all four rows. On master 6ee563b the same script gives all_1_1_0_5 and 4 4 4, as in the issue. I added Closes: #122940 to the description.

On patch parts: attachRestoredParts is the only place this PR adds a mutation reset, and no patch part reaches it. backupData (both engines) takes its parts from getVisibleDataPartsVector, which returns DataPartKind::Regular only, so a backup never contains a patch part (#116677). Measured after UPDATE src SET v = 5 WHERE id = 1: the backup holds only all_1_1_0 on 26.3, 26.6, 26.8, 26.9, master and this PR, and the restored row reads 0. The other two adoption sites, fillNewPartNameAndResetLevel (ATTACH) and ReplicatedMergeTreeSink::writeExistingPart (replicated ATTACH and restore), already set mutation = 0 for every part, patch parts included, on master.

Once #116677 puts patch parts into backups, that change would also have to remap each patch's source_parts.dat (it names the source table's parts, and the restore renumbers every part), so the version question belongs there.

Conflict in StorageMergeTree::attachRestoredParts: master added a check
of the temporary table size limits before the parts are committed
(ClickHouse#124587). Keep that check first and declare reset_level after it; the
check reads only part sizes, so the level and mutation reset do not
affect it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
…he backup

RESTORE compares the existing table definition with the one in the backup
unless `allow_different_table_def` is set, and rejects a mismatch before any
data is inserted. When the comparison passed, the restored parts were merged
with the same merge semantics, so their level is valid and is now kept. That
leaves FINAL and `optimize_skip_merged_partitions` working on a restored table
that already had fully merged parts, instead of going through the collapsing
path until an explicit `OPTIMIZE ... FINAL`.

The level is still reset when the comparison did not run (the setting above,
a predefined table, `restore_replicated_merge_tree_to_shared_merge_tree`), for
the inner table of a materialized view, whose definition is not checked on its
own, and always for `GraphiteMergeTree`: its definition names only a config
section, and the rollup rules resolved from it, which `hasSameMergeSemantics`
treats as merge semantics, can differ on the restoring server.

The decision is made once per table in `restorePartsFromBackup`, for both
engines. `ReplicatedMergeTreeSink::writeExistingPart` no longer touches the
level; replicated `ATTACH PART` from `detached/` resets it in
`attachPartitionImpl` instead, as before.

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

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8118307

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

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05316_secret_arguments_declared_by_engines not from this PR: the test came with #123364, and under DatabaseReplicated its last query_log check counts the CREATE DICTIONARY row twice (0 2 instead of 0 1; the password stays hidden). 180 PRs show it in this lane since 2026-10-02 #124928 (external, merged 17:58Z). This run was dispatched at 15:15Z, before that merge, so I will merge master here to pick it up
Mergeable Check, PR praktika rollups of the row above (Failed: Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2)) #124928 (external, merged)
CH Inc sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261009-220010

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

One query was flagged: clickbench Q20 got -41.4% faster (220 ms to 129 ms), and its CPU time roughly halved. The change is large and consistent enough that the verdict stays locked as an improvement. However, this PR only changes how part levels and mutation versions are reset during RESTORE and ATTACH PART, and the level reset only matters for Replacing, Summing, Aggregating, Collapsing and Graphite engines. ClickBench reads a plain MergeTree table with no FINAL, so nothing in this diff explains the speedup. A difference between the PR build and the master baseline build is the more likely cause, and the speedup should not be credited to this PR without a rerun against an exact-base baseline.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 129 -41.4% <0.0001 Kept because the change is large enough that the verdict is locked. The diff only changes part levels on restore/attach for non-Ordinary engines, and this plain MergeTree scan never runs that code, so the cause is unexplained.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: b89a08da-bbe0-45ff-9de4-ac10e316f486
  • MIRAI run: c27cd161-07e3-42b4-9cea-aa1cd6678e5f
  • PR check IDs:
    • clickbench_98767_1791941933
    • clickbench_98789_1791941933
    • clickbench_98972_1791941936
    • tpch_adapted_1_official_99106_1791941960
    • tpch_adapted_1_official_99209_1791941964
    • tpch_adapted_1_official_99328_1791941982

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

4 participants