Repository navigation
Conversation
…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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-4:20260707-163700 |
|
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 ( |
There was a problem hiding this comment.
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]>
|
Done in e377db8. Switched to |
|
Workflow [PR], commit [6aa713d] Summary: ✅
AI ReviewSummaryThis PR fixes the two foreign-provenance bits that made adopted parts unsafe to trust: Final Verdict
|
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]>
|
The test is now That also closes something I flagged earlier on this PR as untested locally: the replicated half of 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. |
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.
Build profile diff (arm_release)Commit See the job log for details. |
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]>
Internal second-model review of this changeI run every change past an independent cold review plus a second model before pushing. Verdicts
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260828-122300 |
|
cc @CurtizJ @tavplubix, could you review this? A part adopted from |
CI finish ledger - b3d0089Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Not caused by this PR. The diff is Attribution read off the frames rather than the signature: of the visible trace, Same-tree negative control: Session id: cron:our-pr-ci-monitor:20260828-233000 |
|
Similar #122940 |
|
Yes, this PR fixes #122940: the restore site, On patch parts: Once #116677 puts patch parts into backups, that change would also have to remap each patch's |
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]>
…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]>
CI finish ledger - 8118307Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261009-220010 |
|
📊 Cloud Performance Report 🟢 AI verdict: 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)
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
|
Closes: #109674
Closes: #122940
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
SELECT ... FINALsilently returning duplicate rows afterALTER TABLE ... ATTACH PART/ATTACH PARTITION,SYSTEM RESTORE REPLICAor a restore from backup adopted a merged part with duplicate sorting keys into aReplacingMergeTree,SummingMergeTree,AggregatingMergeTreeor anotherFINAL-relying engine. A part attached fromdetached/no longer carries the source table's merge level, a restored part keeps it only whenRESTOREhas 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. TwoFINALconsumers read a non-zero level as "ORDER BY keys already collapsed":PartsSplitterskips the collapsing transform, andReadFromMergeTree'sdo_not_merge_across_partitions_select_finalpath skips post-processing entirely with one part per partition. Since20e5dfc789fthe ATTACH sites clamped an adopted level to 1, the value both consumers trust, so duplicates survived and queries silently returned wrong results.ATTACH PART/PARTITIONnow resets the level, infillNewPartNameAndResetLeveland, for replicated tables andSYSTEM RESTORE REPLICA, inattachPartitionImpl.RESTOREresets it inrestorePartsFromBackupunless the table definition was compared with the backup and matched, so a same-definition restore keeps theFINALfast path.allow_different_table_def, a predefined table, the inner table of a materialized view and everyGraphiteMergeTree(its rollup rules come from the server config) are reset. Every reset also clears the legacy-max-level flag thattryParsePartNamesets for a level field of4294967295.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 plainMergeTreetoo. 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
FINALpath until an explicitOPTIMIZE ... FINAL. Adetached/directory carries no definition to check.Level after adoption for a source part with level > 0, and test coverage
MergeTreeATTACH PART/PARTITION,SYSTEM RESTORE REPLICAGraphiteMergeTree: 0)The mutation version is 0 everywhere. A replicated restore now keeps a plain
MergeTreelevel like the non-replicated one (master: 0); it has noFINALmeaning 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 ... FINALrepairs it. The cross-table clone pathgetLevelForAdoptedPartis untouched: it has its ownhasSameMergeSemanticscheck.tests/integration/test_attach_foreign_part_level_resetcovers ATTACH into the three engines plusReplicatedReplacingMergeTreeand a legacy-max-level part name; no supported statement stages a foreign part indetached/.04402_restore_foreign_part_level_reset_finalcovers a non-replicated restore withallow_different_table_def,05345_restore_part_level_same_definitionthe same-definition restores (both engines), a replicated one withallow_different_table_defandGraphiteMergeTree.03283_optimize_on_insert_levelpinned the old level-1 part names, so its reference is updated.Workflow [PR]
Sync PR [sync-upstream/pr/109686]