Skip to content

Keep invalidated_system_columns.txt when cloning a data part - #115979

Merged
alexey-milovidov merged 17 commits into
masterfrom
keep-invalidated-system-columns-on-clone
Sep 26, 2026
Merged

alexey-milovidov merged 17 commits into
masterfrom
keep-invalidated-system-columns-on-clone

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Closes: #107501
Related: #111801

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 lightweight UPDATE for parts adopted from another table via REPLACE PARTITION or ATTACH PARTITION FROM: after such a part was cloned again (by a mutation that does not modify it, by a clone instead of a fetch of a replicated mutation, or by a move between disks), applying patch parts could silently drop updated rows in release builds and raise the current_version != existing_version exception in debug and sanitizer builds.

Description

Logical error: 'current_version != existing_version' in PatchJoinCache::Entry::addBlock has been failing the AST fuzzer and stress tests for months (failure history, STIDs 2508-3ef8 and 2508-399f).

The assertion means: one patch part contains two rows with the same (_block_number, _block_offset) target and the same _part_data_version. Since _part_data_version is constant per patch part, this happens exactly when a single lightweight UPDATE reads two physical rows carrying the same (_block_number, _block_offset) identity — i.e. when the table's row identities are not unique.

How duplicate identities appear. The failures before 2026-07-27 came from partition adoption itself: the fuzzer turned the REPLACE PARTITION in 03100_lwu_39_after_replace_partition into a self-ATTACH PARTITION ALL, which hardlink-clones every part while keeping the physically stored _block_number/_block_offset columns, instantly duplicating every row identity. That path was fixed by #111801, which writes an invalidated_system_columns.txt marker into the clone, making reads regenerate the identities from the part name.

The remaining hole (this PR). writeInvalidatedSystemColumnsFileImpl unconditionally removed an existing invalidated_system_columns.txt and, for an empty set of columns, wrote nothing back. Every clone that passes no invalidated_columns_to_write — the untouched-part clone in MutateTask (tmp_clone_), the clone-instead-of-fetch of a replicated mutation, moves between disks — therefore deleted the file it had just hardlinked or copied from the source part, resurrecting the stale identities. This is confirmed by the one CI failure whose branch already contained #111801 (Stress test (arm_tsan) on #113029): 03920_replace_partition_mutation_race.sh adopted parts between src and dst, a fuzzed ALTER UPDATE ... WHERE p = 2 cloned the untouched partition-1 parts and dropped their invalidation markers, and a fuzzed lightweight UPDATE then captured the duplicate identities into one patch part; a later mutation applied it in Join mode and aborted.

Deterministic reproduction (aborts a debug build on current master at the final SELECT, both for full and packed part storage):

SET enable_lightweight_update = 1, mutations_sync = 2, apply_patch_parts = 1;
CREATE TABLE src (p UInt8, x UInt64, y UInt64) ENGINE = MergeTree PARTITION BY p ORDER BY x
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
CREATE TABLE dst (p UInt8, x UInt64, y UInt64) ENGINE = MergeTree PARTITION BY p ORDER BY x
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1,
         apply_patches_on_merge = 0, patch_parts_version = 'v1';
INSERT INTO src VALUES (1, 1, 0);
INSERT INTO src VALUES (1, 2, 0);
OPTIMIZE TABLE src PARTITION 1 FINAL;            -- persists _block_number/_block_offset physically
ALTER TABLE dst REPLACE PARTITION 1 FROM src;    -- clone #1, identities invalidated
ALTER TABLE dst ATTACH PARTITION 1 FROM src;     -- clone #2, identities invalidated
ALTER TABLE dst UPDATE y = y + 1 WHERE p = 2;    -- untouched-part clone loses the invalidation file
UPDATE dst SET y = y + 100 WHERE 1;              -- one patch part captures the duplicate identities
OPTIMIZE TABLE dst PARTITION 1 FINAL;            -- renames the patch's source parts away
SELECT * FROM dst ORDER BY x;                    -- Join-mode patch application, aborts

The fix is in two places:

  • writeInvalidatedSystemColumnsFileImpl keeps an existing file when the caller has nothing new to invalidate; this covers the clones that copy or hardlink the whole part directory.
  • cloneAndLoadDataPart merges the source part's invalidated set into the clone parameters; this also covers the Packed storage, whose freeze/freezeRemote copy only the data archive, so the destination never inherits the file.

Verified locally: the reproduction (and its Packed-storage variant) aborts an unfixed debug build and keeps unique identities and correct results on a fixed build; the new test 03100_lwu_56_mutation_clone_keeps_invalidated_columns fails on an unfixed build in any build type (the identity-uniqueness check returns 0) and passes on the fixed one.

Note for releases without #111801 (26.7 and older): they are exposed to the original adoption flavor of this family, so a backport of this fix alone is not sufficient there — it needs #111801 first.


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

Version info

  • Merged into: 26.10.1.767-master (included in 26.10 and later)

A clone of a part that passes no invalidated_columns_to_write (the
untouched-part clone in a mutation, clone-instead-of-fetch of a
replicated mutation, moves between disks) used to delete the
invalidated_system_columns.txt it had just hardlinked or copied from
the source part: writeInvalidatedSystemColumnsFileImpl unconditionally
removed the existing file and wrote nothing back for an empty set.
Losing the file resurrects the stale physically stored _block_number
and _block_offset values that were disclaimed when the part was adopted
from another table (#111801), so several co-active clones of one source
part expose duplicate row identities.

A lightweight UPDATE then captures the duplicates into a single patch
part with a constant _part_data_version, and applying that patch in
Join mode fails the 'current_version != existing_version' assertion in
PatchJoinCache::Entry::addBlock, which aborts debug and sanitizer
builds; release builds silently drop one of the duplicate rows.

Fix in two places:
- writeInvalidatedSystemColumnsFileImpl keeps an existing file when the
  caller has nothing new to invalidate; this covers the clones that
  copy or hardlink the whole part directory.
- cloneAndLoadDataPart merges the source part's invalidated set into
  the clone parameters; this also covers the Packed storage, whose
  freeze/freezeRemote copy only the data archive, so the destination
  never inherits the file.

Failure history:
https://play.clickhouse.com/play?user=play&tab=Query%20V#U0VMRUNUIGNoZWNrX3N0YXJ0X3RpbWUsIHB1bGxfcmVxdWVzdF9udW1iZXIsIGNoZWNrX25hbWUsIHRlc3RfbmFtZSBGUk9NIGNoZWNrcwpXSEVSRSB0ZXN0X25hbWUgTElLRSAnJWN1cnJlbnRfdmVyc2lvbiAhPSBleGlzdGluZ192ZXJzaW9uJScgQU5EIGNoZWNrX3N0YXJ0X3RpbWUgPj0gbm93KCkgLSBJTlRFUlZBTCAzIE1PTlRICk9SREVSIEJZIGNoZWNrX3N0YXJ0X3RpbWU=

The reproduced CI failure (the only one on a branch that already had
the invalidation mechanism from #111801):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113029&sha=cebdc42b01538df822d2da154bb5b51f1d4538d6&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
#113029

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [344b183]

Summary: ✅


AI Review

Summary

This PR fixes the main invalidated_system_columns.txt propagation holes for cloned parts and closes the earlier top-level zero-copy bookkeeping leaks. The remaining issue is that the projection-side bookkeeping still assumes the parent part's clone mode, so a full part with a packed projection can still leak the source projection blob on zero-copy untouched-part mutations. The new integration coverage also leaves MinIO cleanup in flight between tests, which makes the module timing-dependent.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:12791] Packed projections still violate the "record only actually hardlinked blobs" contract. The new loop now matches files_to_copy_instead_of_hardlinks on the bare name, but it still only checks cloneCopiesWholeArchive(params) on the top-level part. In a realistic mixed-format case where the parent part is Full but a projection is Packed, a zero-copy untouched-part mutation copies the whole projection archive because checksums.txt is archived there; this code then records the remaining projection members as hardlinked anyway, so unlockSharedDataByID keeps the source projection blob alive after the clone owns a fresh archive. The projection loop needs per-projection archive-copy detection, mirroring the top-level cloneCopiesWholeArchive(params) exclusion, and the regression should force a packed projection.

⚠️ Majors

  • [tests/integration/test_zero_copy_invalidated_system_columns/test.py:154] The new MinIO integration module does not restore a stable object-store baseline before moving from the first test to the second. DROP TABLE ... SYNC is not sufficient here — other S3 tests explicitly wait for blob cleanup afterwards — so objects_before in the second test can be captured while the first warm-up table is still deleting, and then become unreachable once that deletion finishes. Add a final wait after dropping warming_up and warming_up_proj.
Final Verdict

Request changes.

LLVM Coverage Report

Measured on commit 344b183.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 54/58 (93.10%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 344b18302 with master a32c4c20b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

11 translation units recompiled, 90 s compile time in total, 11 of them have a recent master baseline.

Job report

…b count

The regression test only exercised `Full` part storage, so the
`cloneAndLoadDataPart` half of the fix - the one that matters for
`Packed` parts, whose `freeze`/`freezeRemote` copy only the data archive
and therefore inherit no `invalidated_system_columns.txt` - was only
covered probabilistically. Pin `min_bytes_for_full_part_storage` in both
cases, assert `part_storage_type` in `system.parts`, and run the whole
scenario twice, for `Full` and for `Packed`.

Verified locally: with the `cloneAndLoadDataPart` change reverted, the
`Packed` case reports duplicate `(_block_number, _block_offset)` pairs
after the untouched-part clone, while the `Full` case still passes.

`test_merge_tree_s3/test.py::test_move_replace_partition_to_another_table`
failed with `assert 62 == 60` after `DROP TABLE s3_test SYNC`. That is a
consequence of this change and not a flake: `freeze` passes an empty
`invalidated_columns_to_write`, so the frozen copies of the two adopted
parts used to lose the hardlinked `invalidated_system_columns.txt` and
its blobs were collected with the table. They are now kept - which is the
point of the fix, a restored backup must not resurrect the disclaimed
`_block_number`/`_block_offset` either - so the expected object count
after the drop gains `FILES_OVERHEAD_PER_INVALIDATED_COLUMN * 2`.

Failing CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115979&sha=034a7276271bee56fb728b2b3192dab0cb147968&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%205%2F6%29
#115979
… paths

The file is written separately, next to `data.packed`, so
`DataPartStorageOnDiskPacked::freeze`/`freezeRemote` carried only the
archive and dropped it whenever the caller had no invalidated columns of
its own (`freezePartitionsByMatcher` on `ALTER TABLE ... FREEZE`,
`makeCloneInDetached` on `DETACH`). Copy it from the source part
explicitly, same as the `Full` storage freeze inherits it by hardlinking
every file of the part. Fixing it at the storage layer covers all direct
`freeze` callers and keeps the `Full` path (and its S3 blob accounting)
untouched.

The new test checks the frozen and detached copies on the filesystem,
because a plain `ATTACH` masks the loss at the SQL level:
`loadPartAndFixMetadataImpl` unconditionally re-invalidates
`_block_number`/`_block_offset` for every attached part.
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
alexey-milovidov and others added 4 commits September 9, 2026 14:54
…dlinked when the clone owns it

`cloneAndLoadDataPart` records every file of the source part in
`hardlinked_files->hardlinks_from_source_part`, which `unlockSharedDataByID` later uses as
`files_not_to_remove`. But the destination does not always share
`invalidated_system_columns.txt` with the source: a non-empty
`invalidated_columns_to_write` makes every freeze path remove the inherited file and write a
fresh one, and packed storage never hardlinks the file at all (only `data.packed` is
hardlinked, and the file is written separately next to it). In both cases the source blob was
kept alive for a child that does not reference it, leaking it once the source part was
removed on zero-copy object storage.

Exclude the file from the hardlink list exactly in those cases; the full-storage clone that
inherits the file (an empty set) still records it, because there it really is a hardlink.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`master` gained `03100_lwu_57_lock_acquire_timeout.sh` meanwhile, so move this test to
`03100_lwu_59_freeze_detach_keep_invalidated_columns.sh` to keep the lightweight-update test
numbers unique.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ardlink list

The new integration test runs the untouched-part mutation clone of an adopted part on a
`ReplicatedMergeTree` over object storage with zero-copy replication, and checks the hardlink
list that the clone records in the source part's zero-copy node in Keeper: the list must be
non-empty (so the check is not vacuous) and must not contain
`invalidated_system_columns.txt`, because the clone writes its own copy of that file. It also
checks that no object is left in the object storage once both tables are dropped.

Verified locally: the test passes, and it fails on a control binary where the exclusion is
disabled, with the recorded list containing `invalidated_system_columns.txt`. The mutation is
asserted to have taken the untouched-part path via the `MutationUntouchedParts` profile event -
a predicate that the partition can prune never reaches it on a replicated table.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was 4356 commits behind) and pushed ac44014; the three touched translation units compile clean, the diff is unchanged.

The only red on acb3f07 was Fast test -> 01660_system_parts_smoke: Bad get: has Int128, requested UInt128 (BAD_GET) in MergeTreePartition::serializeText while reading system.parts. That is a pre-existing bug for a PARTITION BY with modulo of an unsigned by a signed operand (a concurrently running test created such a table); this PR does not touch partition serialization. The fix is in progress by @groeneai in #119333. Everything downstream (builds, Bugfix validation, new_tests_check) was dropped because of that Fast test failure, so the rerun on the new head should restore them.

alexey-milovidov and others added 4 commits September 21, 2026 01:43
The clone decides copy-vs-hardlink inside a projection directory on the
bare file name (`BackupImpl` recursing into the projection, and packed
projection `freeze` receiving the same `params`). The projection loop in
`cloneAndLoadDataPart` matched `files_to_copy_instead_of_hardlinks` against
the prefixed name, so an untouched-part mutation on a zero-copy table
recorded `prj.proj/checksums.txt` as hardlinked although it was copied, and
`unlockSharedDataByID` kept the source blob alive - leaked.

Address review: #115979 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 I merged master and pushed 344b18302f60, which also adds the projection hardlink bookkeeping fix from the review thread. Reds on the previous head 5f45512cf3b3 that are not caused by this PR:

  • Upgrade check (amd_release): Part A intersects previous part B (STID 3562-39cd). This one is fleet-wide: it hit about 10 PRs and several master stress runs between 2026-09-17 and 2026-09-26. It is tracked in Logical error: Part A intersects next part B. It is a bug or a result of manual intervention (STID: 3562-39cd) #122212, and @groeneai is already investigating (it comes from the previous-release binary during the stress phase).
  • Performance Comparison (arm_release, 2/6, 3/6): set_index, file_table_function, min_max_wide_integers. This PR does not touch those query paths, and the runner was labelled disk-almost-full / under-utilized CPU.

/// projection `freeze` receiving the same `params`). Matching on the prefixed name would record
/// e.g. `p.proj/checksums.txt` as hardlinked although the untouched-part mutation copied it,
/// so zero-copy would keep the source blob alive for a child that does not reference it.
if (!params.files_to_copy_instead_of_hardlinks.contains(it->name())

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 projection-side zero-copy bookkeeping is still incomplete for packed projections. cloneAndLoadDataPart only consults cloneCopiesWholeArchive(params) on the top-level part, but this loop iterates each projection's own storage. On an untouched-part mutation with zero-copy enabled, files_to_copy_instead_of_hardlinks = {'checksums.txt'} makes a packed projection copy its whole archive because checksums.txt lives inside data.packed; after that, none of the projection's archived members are hardlinked from the source anymore. This branch now skips prj.proj/checksums.txt, but it still records the rest of the projection members as hardlinked, so unlockSharedDataByID keeps the source projection blob alive even though the child owns a fresh archive. The projection loop needs the same per-storage cloneCopiesWholeArchive(params) handling as the top-level loop, and the regression should force a packed projection case.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Zero-copy replication does not matter.

# And nothing is left behind in the object storage once both tables are dropped.
wait_blobs_synchronization(cluster.minio_client, objects_before)

node1.query("DROP TABLE warming_up SYNC")

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.

These tests share one module-scoped MinIO cluster, but after DROP TABLE warming_up SYNC the test returns without waiting for the corresponding S3 objects to disappear. The next test then snapshots objects_before against whatever is still present; if the first warm-up table finishes deleting later, wait_blobs_synchronization(..., objects_before) in the second test can never reach that older object set and the module becomes timing-dependent. Other S3 tests wait after dropping the warm-up table for exactly this reason. Please add a final stable-baseline wait here (for example wait_blobs_count_synchronization(cluster.minio_client, 0), and the same after warming_up_proj) before leaving each test.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into master with commit 11bcd5f Sep 26, 2026
173 checks passed
@alexey-milovidov
alexey-milovidov deleted the keep-invalidated-system-columns-on-clone branch September 26, 2026 21:00
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
@clickhouse-gh clickhouse-gh Bot added comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: 'current_version != existing_version' (STID: 2508-3ef8)

2 participants