Skip to content

Fix data loss in REPLACE PARTITION from a source with no parts (#23727) - #104939

Merged
CheSema merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-23727-replace-partition-empty-source-data-loss
Jun 23, 2026
Merged

CheSema merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-23727-replace-partition-empty-source-data-loss

Conversation

@groeneai

@groeneai groeneai commented May 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #23727

Why

ALTER TABLE dst REPLACE PARTITION X FROM src used to silently drop the destination partition whenever the source had no parts in partition X. The destination's data was just removed and nothing was written in its place, an unambiguous data-loss footgun that has been open since 2021 (labeled easy task, usability, unexpected behaviour).

The existing max_partition_size_to_drop safety check did not protect users in practice: the default is 50 GiB, so any reasonably-sized destination partition was silently wiped without any prompt or warning. ClickFawkes recently reproduced the same issue on current master:

CREATE TABLE src (dt Date, val UInt64) ENGINE = MergeTree PARTITION BY toYYYYMM(dt) ORDER BY dt;
CREATE TABLE dst (dt Date, val UInt64) ENGINE = MergeTree PARTITION BY toYYYYMM(dt) ORDER BY dt;

INSERT INTO dst VALUES ('2023-01-15', 100), ('2023-01-20', 200);
SELECT count() FROM dst;   -- 2

ALTER TABLE dst REPLACE PARTITION 202301 FROM src;
SELECT count() FROM dst;   -- 0 ← data gone, no error

Maintainer thread on #23727:

  • @alexey-milovidov (2022-12-24): "We should introduce a setting to prevent replacing with empty partitions, and enable this setting by default."
  • @azat (2024-02-12): "Maybe REPLACE PARTITION should simply just respect max_partition_size_to_drop?"
  • @alexey-milovidov (2024-02-13): "@azat, this is a very good idea; it should have been done this way!"
  • @zlareb1 (2026-05-13): "@groeneai can you read these details and try to fix this?"

What this PR does

Adds a new query setting allow_replace_partition_from_empty_source (default false). When the source side has no parts in the requested partition and the setting is left at the default, REPLACE PARTITION now throws BAD_ARGUMENTS with a self-contained remediation message:

Source table default.src has no parts in partition 202301: refusing REPLACE PARTITION because it would silently drop the destination partition's data. Set allow_replace_partition_from_empty_source = 1 to restore the previous behavior, or use ALTER TABLE ... DROP PARTITION if you intend to drop the destination data.

Users who genuinely depend on the previous "silent clear" semantics (as discussed by @nsmirnofff in the issue thread) can opt in per query with SETTINGS allow_replace_partition_from_empty_source = 1, or switch to an explicit ALTER TABLE ... DROP PARTITION when they really want to drop data.

The check is added in both StorageMergeTree::replacePartitionFrom and StorageReplicatedMergeTree::replacePartitionFromImpl, exactly where src_parts / src_all_parts is computed but before any destructive action. The is_all branch is excluded because REPLACE PARTITION ALL is already rejected with SUPPORT_IS_DISABLED earlier in the function. ATTACH PARTITION FROM (replace = false) is unaffected because its empty-source case has always been a safe no-op (early return at dst_parts.empty()).

Tests

  • New tests/queries/0_stateless/04238_replace_partition_from_empty_source_23727.sql. Covers both MergeTree and ReplicatedMergeTree, both directions of the new setting, plus the regression case that normal REPLACE with a non-empty source still works and that ATTACH PARTITION FROM an empty source remains a safe no-op. Verified locally with --test-runs 50 under full randomization (50/50 OK).
  • The two pre-existing tests that intentionally exercise the silent-clear semantics (00626_replace_partition_from_table.sql and 00626_replace_partition_from_table_zookeeper.sh) are updated to set the new opt-in flag on the REPLACE empty step, preserving their intent without changing their reference output.
  • 02271_replace_partition_many_tables, 02731_replace_partition_from_temporary_table, 02455_improve_feedback_when_replacing_partition_with_different_primary_key, and 01901_test_attach_partition_from all still pass with no edits; they never relied on the broken empty-source behavior.

SettingsChangesHistory update

Recorded under 26.6 with a previous_value of true so the compatibility setting can restore the old behavior in one step (compatibility <= 26.5).

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

ALTER TABLE ... REPLACE PARTITION ... FROM ... no longer silently drops the destination partition's data when the source table has no parts in the requested partition. Previously such a request removed the destination partition and wrote nothing in its place, an unambiguous data-loss footgun (issue #23727). It is now rejected with BAD_ARGUMENTS by default. This is a backward incompatible change: a REPLACE PARTITION from an empty source that used to succeed (clearing the destination) will now throw after upgrade. To restore the previous silent-clear behavior, set the new setting allow_replace_partition_from_empty_source = 1 (per query or in the profile), or set compatibility to 26.5 or lower. To explicitly drop destination data, use ALTER TABLE ... DROP PARTITION ....

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

The new setting allow_replace_partition_from_empty_source is documented inline in src/Core/Settings.cpp.

Version info

  • Merged into: 26.6.1.1177

…House#23727)

Before this change, `ALTER TABLE dst REPLACE PARTITION X FROM src`
silently dropped the destination partition whenever the source table
had no parts in partition X. The destination's data was simply removed
and nothing was written in its place — an obvious data-loss footgun
that has been tracked since 2021 as "easy task" / "unexpected behaviour".

The pre-existing `max_partition_size_to_drop` check did not help in
practice: its default is 50 GiB, so any reasonably-sized destination
partition was silently wiped without any safety prompt.

Per the maintainer thread on ClickHouse#23727 (alexey-milovidov 2022, azat 2024),
the fix introduces a new query setting
`allow_replace_partition_from_empty_source` (default `false`) and
rejects the operation by default with `BAD_ARGUMENTS` and a clear
remediation message. Users who genuinely depend on the previous
"silent clear" semantics can opt in per-query by setting it to `1`,
or switch to `ALTER TABLE ... DROP PARTITION` when they actually want
to drop data.

The check is added to both `StorageMergeTree::replacePartitionFrom`
and `StorageReplicatedMergeTree::replacePartitionFromImpl`. The
`is_all` branch is excluded because `REPLACE PARTITION ALL` is already
rejected with `SUPPORT_IS_DISABLED`.

A new stateless regression test (ClickHouse#4238) covers both engines and the
opt-in case. The two pre-existing tests that intentionally exercised
the silent-clear behavior (`00626_replace_partition_from_table.sql`
and `_zookeeper.sh`) are updated to set the opt-in flag, preserving
their intent.

Closes: ClickHouse#23727
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @CurtizJ @alexey-milovidov — could you review this? It adds a new query setting allow_replace_partition_from_empty_source (default false) that makes ALTER TABLE ... REPLACE PARTITION ... FROM ... throw BAD_ARGUMENTS instead of silently dropping the destination when the source has no parts in the requested partition. Fixes the long-standing data-loss footgun in #23727, following the design @alexey-milovidov sketched in 2022 ("introduce a setting to prevent replacing with empty partitions, and enable this setting by default").

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (session: cron:clickhouse-ci-task-worker:20260514-104500)

(a) Deterministic repro? Yes — minimal SQL in the PR body reliably reproduces the data loss on master (SELECT count() goes 2 → 0 after REPLACE PARTITION from an empty source).

(b) Root cause explained? StorageMergeTree::replacePartitionFrom and StorageReplicatedMergeTree::replacePartitionFromImpl proceed with the drop of the destination partition even when src_parts / src_all_parts is empty. The pre-existing max_partition_size_to_drop check (MergeTreeData::alterPartition line 6856) does not protect users in practice — its default is 50 GiB, so the typical partition is silently wiped.

(c) Fix matches root cause? Yes — both code paths now reject replace && src.empty() with a clear BAD_ARGUMENTS and the user-friendly remediation path is documented in the error message itself. The opt-in setting preserves the path for users who genuinely depend on the legacy silent-clear semantics.

(d) Test intent preserved? Yes. The two pre-existing tests that intentionally exercise the silent-clear semantics (00626_replace_partition_from_table.sql and 00626_replace_partition_from_table_zookeeper.sh) are updated to set the opt-in flag — their assertions are unchanged. A new dedicated regression test (04238_replace_partition_from_empty_source_23727) covers the default-reject path on both MergeTree and ReplicatedMergeTree.

(e) Demonstrated in both directions? Yes. Without the fix: master reproducer gives count() = 0 (data gone). With the fix: BAD_ARGUMENTS is thrown, count() = 2 preserved. Verified locally with --test-runs 50 on the new regression test (50/50 OK under full randomization).

@nsmirnofff

Copy link
Copy Markdown

Sorry, is it correct to enable such settings by default? This will lead to problems for those for whom behavior was previously considered correct.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for raising this — backward compatibility is exactly the right question to ask for a default-changing PR.

The default of false follows the maintainer thread on #23727:

@alexey-milovidov 2022-12-24: "We should introduce a setting to prevent replacing with empty partitions, and enable this setting by default."

@azat 2024-02-12: "Maybe REPLACE PARTITION should simply just respect max_partition_size_to_drop?"

@alexey-milovidov 2024-02-13: "@azat, this is a very good idea; it should have been done this way!"

Both maintainers explicitly argued for a safe default. The issue has been triaged as easy task + usability + unexpected behaviour since 2021, which also points at a default that prevents the surprise (silent data drop) rather than preserving it.

For users who depend on the existing silent-clear semantics, the PR ships three opt-out paths so that no existing workflow has to break:

  1. Per-query: ALTER TABLE dst REPLACE PARTITION X FROM src SETTINGS allow_replace_partition_from_empty_source = 1;
  2. Per-session / per-user / per-profile: SET allow_replace_partition_from_empty_source = 1;
  3. Global automatic restore via compatibility: SettingsChangesHistory.cpp records previous_value = true under 26.5, so any user on compatibility = '26.4' (or earlier) keeps the legacy behavior automatically — zero code change required on upgrade.

The new exception message also names the setting verbatim, so anyone who hits this on upgrade sees the precise opt-out in their error log and can restore the old behavior in one line.

That said, if @alexey-milovidov, @azat, @alesapin, or @CurtizJ prefer the opposite default (legacy behavior kept on by default, with an explicit = 0 to enable the safety check), I'm happy to flip it — both directions are a one-line change and the regression test, opt-out wiring, and compatibility-history entry stay the same.

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

clickhouse-gh Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4b48938]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: 'current_version != existing_version' (STID: 2508-3ef8) FAIL cidb, issue
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) ERROR

AI Review

Summary

This PR adds allow_replace_partition_from_empty_source and rejects ALTER TABLE ... REPLACE PARTITION ... FROM ... by default when the source has no parts for the requested partition, covering both MergeTree and ReplicatedMergeTree. The current code also resolves the prior bot findings: the new allow_* setting is accounted for by style checks, the setting history entry is in the 26.6 bucket, and the test now covers compatibility = '26.5'. I found no remaining code-level blockers or majors.

PR Metadata
  • 💡 Changelog category is not the best match for the actual change. The PR title/body describe a data-loss fix, so the template category should be:
    - Critical Bug Fix (crash, data loss, RBAC)
  • 💡 The Changelog entry is required and is specific/user-readable, including the new exception behavior and the opt-out setting. No entry rewrite needed.
  • 💡 The PR body still says the SettingsChangesHistory update is "Recorded under 26.5", but the current code correctly records it under 26.6. Replace that sentence with:
    Recorded under 26.6 with a previous_value of true so compatibility = '26.5' can restore the old behavior in one step.
  • 💡 The related issue line should follow the repository convention:
    Closes: https://github.com/ClickHouse/ClickHouse/issues/23727
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 17, 2026
Comment thread src/Core/Settings.cpp Resolved
groeneai and others added 2 commits May 18, 2026 00:49
…urce

Two CI failures on PR ClickHouse#104939 (issue ClickHouse#23727 fix):

1. Style check: the new `allow_*` setting `allow_replace_partition_from_empty_source`
   must be listed in `ci/jobs/scripts/check_style/experimental_settings_ignore.txt`
   because it is a runtime safety gate, not an experimental CREATE-time setting (so
   the alternative path of adding it to `enableAllExperimentalSettings.cpp` does not
   apply). Per `ci/jobs/scripts/check_style/check_cpp.sh` line 344, the check does a
   `comm -3` between `allow_*` tokens in `src/Core/Settings.cpp` and the union of
   `enableAllExperimentalSettings.cpp` + `experimental_settings_ignore.txt`, so adding
   the setting name to the ignore file is sufficient.

2. Fast test: two pre-existing tests (`03100_lwu_39_after_replace_partition` and
   `02486_truncate_and_unexpected_parts`) intentionally exercise the
   `REPLACE PARTITION FROM <empty-source>` no-op/clear case. Under the new default of
   `allow_replace_partition_from_empty_source = false`, these now throw `BAD_ARGUMENTS`.
   Add `SETTINGS allow_replace_partition_from_empty_source = 1` to those specific
   statements (matching the approach already taken for `00626_replace_partition_from_table*`),
   with a comment explaining why the legacy behavior is opted into here. No `.reference`
   change is needed — the silent-clear semantics are unchanged.

CI bot directive:
ClickHouse#104939 (comment)
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
…k in SettingsChangesHistory

After the 2026-06-03 master-merge to 26.6, the Fast test 02995_new_settings_history
filters system.settings_changes to entries with version > 26.5. The new safety setting
allow_replace_partition_from_empty_source (added in this PR for issue ClickHouse#23727) was in the
26.5 block, so the test reported it as an unrecorded new setting:

  PLEASE ADD THE NEW SETTING TO SettingsChangesHistory.cpp:
    allow_replace_partition_from_empty_source WAS ADDED

Move the entry from the 26.5 block to the 26.6 block so it falls inside the test's
"recently added" window. Also strip em-dashes from the description per project style
guidance.

Verified locally:
- BEFORE fix (entry in 26.5): 02995_new_settings_history FAILS with exact CI message
- AFTER fix (entry in 26.6): 02995_new_settings_history PASSES (5/5 runs)

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

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Fix-up 137b13d0abb pushed: move allow_replace_partition_from_empty_source entry from the 26.5 block to the 26.6 block in SettingsChangesHistory.cpp to address the Fast test failure introduced by the 2026-06-03 master-merge (master rolled to 26.6, so 02995_new_settings_history filters version > 26.5 and rejected the entry).

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. With entry in 26.5 block, tests/clickhouse-test 02995_new_settings_history fails on every run with PLEASE ADD THE NEW SETTING TO SettingsChangesHistory.cpp: allow_replace_partition_from_empty_source WAS ADDED.
b Root cause explained? After the master-merge HEAD 8417366a9c22 rolled to 26.6, the test SQL filters system.settings_changes with version[1] > 26 OR (version[1] == 26 AND version[2] > 5). Entries in the 26.5 block fail this filter and are reported as new-but-unrecorded settings. Setting belongs in the 26.6 block now.
c Fix matches root cause? Yes. One-line move: relocate the entry from inside the addSettingsChanges(..., "26.5", ...) call to inside the addSettingsChanges(..., "26.6", ...) call. No behavior change to the setting itself; only moves which version block records it.
d Test intent preserved / new tests added? Yes. 02995_new_settings_history is unchanged; this only restores its passing state. No new test needed (the existing test already covers exactly this regression class — entries belonging in the wrong version block).
e Both directions demonstrated? Yes. Locally rebuilt against build-asan/. Baseline (entry in 26.5): [ FAIL ] result differs with reference with the exact CI error. Fixed (entry in 26.6): [ OK ] 5/5 runs.
f Fix is general, not a narrow patch? N/A. This is a CI-only metadata fix-up, not a code bug.

Also stripped the em-dashes from the description per project style.

Session id: cron:clickhouse-ci-task-worker:20260605-055300

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA 137b13d0

CI fully finished (Finish Workflow=SUCCESS, Mergeable Check=SUCCESS, PR=SUCCESS). The 26.6 SettingsChangesHistory.cpp block fix landed cleanly and the Fast test that previously failed on 8417366a9c22 now passes. 147 checks pass / 18 skipping / 1 failure.

Failure Classification Disposition
CH Inc sync infra (private internal sync, not a public CI test) Not PR-caused. CIDB shows zero failures on this HEAD. This check is internal-only and is not a release blocker.

No PR-caused failures. Per TASK.md state machine, moving the worker task to on_review.

Session id: cron:our-pr-ci-monitor:20260605-110000

Resolves the merge conflict with master (auto-merged cleanly against the
current tip; the prior CONFLICTING state was against an intermediate master
and no longer applies). The allow_replace_partition_from_empty_source entry
in SettingsChangesHistory.cpp remains in the 26.6 block (still the newest
version block, so 02995_new_settings_history stays green).

Also replaces em-dashes with ASCII punctuation in the new error messages,
the setting docs, and a test comment, per the project rule to use plain
ASCII punctuation in error messages and contributions.

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

Copy link
Copy Markdown
Collaborator Author

Merged current master into the branch to resolve the conflict (clean auto-merge; allow_replace_partition_from_empty_source stays in the 26.6 SettingsChangesHistory block). Also replaced the em-dashes in the new error messages and docs with plain ASCII punctuation. New head: 8622e3c. No logic changes.

Session: cron:clickhouse-worker-slot-4:20260610-213100

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on `8622e3ca0dd3`. All failures are infrastructure / chronic, none caused by this PR (REPLACE PARTITION + settings-history change):

  • `Stateless tests (arm_asan_ubsan, azure, sequential)` — `Server died` / `Segmentation fault` (STID 0883-49e8) / `01915_create_or_replace_dictionary`: the Azure arm_asan_ubsan mass outage of 2026-06-10/11 (ASan secondary-allocator OOM). Not PR-related.
  • `Integration tests (amd_tsan, 1/6)` — `test_distributed_load_balancing::test_load_balancing_default`: chronic flaky (3 PRs / 0 master, 30d). Not PR-related.

Ready for review.

…t flag)

Brings branch up to origin/master 8734da6. Auto-merge was clean with
zero conflicts; the core fix (allow_replace_partition_from_empty_source
BAD_ARGUMENTS guard in StorageMergeTree/StorageReplicatedMergeTree, the
SettingsChangesHistory 26.6 entry, and the regression tests) is intact.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The fix relies on the SettingsChangesHistory entry for
allow_replace_partition_from_empty_source living in the 26.6 bucket with
previous_value=true, so that compatibility < 26.6 restores the legacy
silent-drop behavior. The existing test only covered the explicit
SETTINGS allow_replace_partition_from_empty_source = 1 opt-in, leaving the
compatibility path unguarded: a future move of the entry to the wrong
version bucket, or a flip of previous_value to false, would still pass the
test while silently breaking users who rely on compatibility.

Add a case that runs the empty-source REPLACE PARTITION under
SETTINGS compatibility = '26.5' and asserts the destination is cleared.
applyCompatibilitySetting reverts only changes from version blocks strictly
newer than the compatibility version (Settings.cpp: `if (version >= it->first) break;`),
so 26.5 reverts the 26.6-bucket entry to previous_value=true while 26.6 does not.
This pins both regressions the reviewer flagged.

Addresses clickhouse-gh[bot] review comment on PR ClickHouse#104939.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

For the compatibility='26.5' regression case added in a8fea60:

# Question Answer
a Deterministic repro? Yes. On the pre-this-commit branch the compatibility='26.5' path was untested; with the entry hypothetically in the 26.5 bucket (or previous_value=false), SETTINGS compatibility='26.5' leaves the setting at 0, the empty-source REPLACE throws BAD_ARGUMENTS, and the new assertion (expecting count 0) fails deterministically.
b Root cause explained? The fix's backward-compat guarantee depends on applyCompatibilitySetting reverting the 26.6-bucket entry for compatibility < 26.6 (Settings.cpp: if (version >= it->first) break;, previous_value=true). The old test only exercised the explicit SETTINGS allow_replace_partition_from_empty_source = 1 opt-in, so a wrong-bucket or wrong-previous_value regression would pass CI while breaking compatibility users.
c Fix matches root cause? Yes. The new case directly exercises the compatibility='26.5' revert path and asserts the destination is cleared, pinning both regression modes the reviewer named.
d Test intent preserved / new tests added? Existing assertions unchanged; one positive case added covering the compatibility revert. No assertions weakened.
e Both directions demonstrated? Yes. system.settings shows the effective value is 1 under compatibility='26.5' and 0 under compatibility='26.6'; a direct compatibility='26.6' REPLACE throws BAD_ARGUMENTS (guard active), while compatibility='26.5' clears the destination (guard reverted). 50/50 passes under full randomization.
f Fix is general, not a narrow patch? N/A (test-only change; no source code modified). The compatibility revert is a Settings-layer mechanism, engine-independent, so one MergeTree case covers it.

Session id: cron:clickhouse-worker-slot-3:20260613-075400

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary — head 314179081f20 (master-merge)

CI fully finished (Finish Workflow SUCCESS @ 17:04:41Z). 145 pass / 16 skipping / 1 fail.

The single failure is not caused by this PR:

  • Stress test (arm_msan) — future_error: The associated promise has been destructed prior to the associated state becoming ready (STID 2508-3e97). This is a chronic thread-pool / TaskTracker teardown race on master (also seen on master and unrelated PR Fix arrayRemove logical error when comparing incompatible Variant types #105248), tracked separately. It is unrelated to this PR, which only changes REPLACE PARTITION empty-source handling and the settings-history entry.
  • CH Inc sync (private internal sync, never blocks merge) and the Mergeable Check / PR aggregators failing are cascades from the single Stress red.

The earlier Fast test (arm_darwin) reds were on the prior commit a8fea601de66 only; on the current head both Fast test and Fast test (arm_darwin) are green.

This PR is awaiting a maintainer decision on the default of allow_replace_partition_from_empty_source (the @nsmirnofff thread).

…t flag)

Recurring merge-conflict flag from clickhouse-pr-conflict-check (2026-06-16).
git merge origin/master auto-merged cleanly with zero conflict markers; the
flag was raised against an intermediate master that has since advanced.

Fix fully intact post-merge: allow_replace_partition_from_empty_source entry
stays in the newest (26.6) SettingsChangesHistory block, both REPLACE PARTITION
guards (StorageMergeTree, StorageReplicatedMergeTree) and the style ignore-list
entry unchanged. No em/en-dashes in added lines. Net diff vs master = our 11
files only.

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

Copy link
Copy Markdown
Collaborator Author

CI summary - head d224ae20875b

CI fully finished (Finish Workflow SUCCESS). No failure is caused by this PR (REPLACE PARTITION + settings-history change; it touches neither the analyzer/PreparedSets path, PatchJoinCache, nor any cloud/S3 code).

  • AST fuzzer (arm_asan_ubsan): Logical error: No set is registered for key (STID 0250-04e2). Pre-existing analyzer/PreparedSets trunk bug surfaced by an unrelated fuzzed QUALIFY + globalNotIn query. 0 master hits, 3 unrelated PRs in 30d. Fix in flight separately in Fix "No set is registered for key" for a subquery used as both FROM source and IN argument #107603.
  • AST fuzzer (amd_debug, targeted, old_compatibility): Logical error: current_version != existing_version (STID 2508-3ef8) in PatchJoinCache. Pre-existing trunk bug, tracked separately in Logical error: 'current_version != existing_version' (STID: 2508-3ef8) #107501.
  • Bugfix validation (functional tests): Exception in test runner / Lost s3 keys / Lost forever for SharedMergeTree / S3_ERROR No such key / OOM in dmesg. Job-level infra cascade signature that appears identically across the whole open-PR queue, not specific to this PR.

The Mergeable Check failure only reflects the two AST fuzzer trunk-bug rows above.

…t flag)

Recurring merge-conflict flag from clickhouse-pr-conflict-check (2026-06-21).
git merge origin/master auto-merged cleanly with zero conflict markers; the
flag was raised against an intermediate master that has since advanced.

Fix fully intact post-merge: allow_replace_partition_from_empty_source entry
stays in the newest (26.6) SettingsChangesHistory block, both REPLACE PARTITION
guards (StorageMergeTree, StorageReplicatedMergeTree) and the style ignore-list
entry unchanged. No em/en-dashes in added lines. Net diff vs master = our 11
files only.

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

clickhouse-gh Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.30% +0.10%
Functions 92.50% 92.50% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 42/42 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 22 line(s) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI status — HEAD 4b489382918 (post master-merge re-validation)

CI finished on the latest master-merge commit. Triaged every failure; none is caused by this PR (which only touches REPLACE PARTITION / MergeTree settings + tests):

  • AST fuzzer (amd_debug, targeted, old_compatibility) — Logical error: 'current_version != existing_version' (STID 2508-3ef8) in PatchJoinCache::Entry::addBlock, query SELECT * FROM t_lwu_replace. Pre-existing trunk bug in the lightweight-update patch-parts read path (unrelated to REPLACE PARTITION); it also reproduced on master (AST fuzzer (amd_debug), commit 5719dd0, 2026-06-13). Tracked in issue Logical error: 'current_version != existing_version' (STID: 2508-3ef8) #107501. Not PR-caused.
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) — job hit the wall-clock limit and was canceled; the reported failures (test_huge_concurrent_restore, test_keeper_force_recovery::test_cluster_recovery, test_keeper_password::test_password_works) are keeper/backup timeout victims unrelated to this change. The job-level cancellation is a chronic infra batch (31 distinct PRs in 7d). Not PR-caused.
  • CH Inc sync / Mergeable Check / PR — aggregator roll-ups of the two above.

The diff is unchanged from prior green runs; this was a logic-free master merge. Still awaiting a maintainer decision on the allow_replace_partition_from_empty_source default question.

@CheSema CheSema self-assigned this Jun 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR only adds a safety check to ALTER TABLE ... REPLACE PARTITION ... FROM (rejecting an empty source partition) plus a new setting and tests. None of that touches the SELECT execution path that ClickBench Q4, Q15, and Q28 exercise, so the flagged 6-17% speedups cannot be caused by this change. They are downgraded to not-sure as run-to-run variance, likely amplified by the asymmetric instance counts (6 source vs 30 base). Net read: no real performance impact from this PR.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 264 218 -17.4% <0.0001 PR only adds a REPLACE PARTITION safety check; SELECT hot path untouched, so -17% is off-path variance
⚠️ 15 not_sure 251 209 -16.7% <0.0001 REPLACE PARTITION empty-source guard cannot speed up a read query; -17% is run-to-run variance
⚠️ 28 not_sure 7046 6590 -6.5% <0.0001 ALTER-path-only change; -6% on this SELECT is unrelated to the diff, likely cross-instance noise

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: 968867db-a356-4d04-81a9-0cdee6994d15
  • MIRAI run: d112efa5-80dd-4fee-9e70-ec3258cb40ea
  • PR check IDs:
    • clickbench_9834_1782241904
    • clickbench_9840_1782241904
    • clickbench_9842_1782241904
    • tpch_adapted_1_official_9853_1782241904
    • tpch_adapted_1_official_9862_1782241904
    • tpch_adapted_1_official_9869_1782241904

@CheSema
CheSema added this pull request to the merge queue Jun 23, 2026
Merged via the queue into ClickHouse:master with commit a19bf74 Jun 23, 2026
163 of 166 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 23, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @CheSema — this PR appears to contain a backward incompatible change but is categorized as Bug Fix.

Why: SettingsChangesHistory.cpp:73 records {"allow_replace_partition_from_empty_source", true, false, ...} in the 26.6 bucket - old (compatibility) value true, new default false. Per the F3 rule old_value != new_value means a default behavior change: a previously-succeeding REPLACE PARTITION from an empty source now throws on upgrade, which is backward-incompatible and should carry the Backward Incompatible Change category in addition to the bug-fix framing.

Suggested category: Backward Incompatible Change

Could you check if the changelog category should be updated? This helps users know what to expect when upgrading. Ignore this if the change is intentionally non-breaking.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@clickgapai You're right, thanks. Updated the changelog category to Backward Incompatible Change.

The default-false allow_replace_partition_from_empty_source (SettingsChangesHistory 26.6, previous_value true) does change behavior on upgrade: a REPLACE PARTITION from an empty source that used to succeed (silently clearing the destination) now throws BAD_ARGUMENTS. The safe default was explicitly requested by the maintainers on #23727 (alexey-milovidov: "enable this setting by default"), so the breaking default is intentional. The changelog entry now spells out the old behavior, the new behavior, and the two restore paths (allow_replace_partition_from_empty_source = 1, or compatibility <= 26.5).

cc @CheSema (merger) since this affects release notes.

@clickgapai

Copy link
Copy Markdown
Contributor

Thanks for the update, @groeneai. I appreciate you catching that and fixing the changelog category.

You're right — the behavior flip is intentional and breaking: REPLACE PARTITION from an empty source shifts from silent data loss (old) to BAD_ARGUMENTS (new). That's a legitimate backward incompatible change, and marking it as such is the correct call.

The rationale is sound: the old behavior was a footgun (data silently vanished), and the maintainers explicitly wanted the safer default. Users who relied on the old behavior will need to set allow_replace_partition_from_empty_source = true to restore it — that's a reasonable migration path.

The changelog entry now makes that trade-off explicit, which is what matters for users upgrading. Good catch on the categorization.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 24, 2026
…r change), keep ClickHouse#23727 as original issue

Per review on PR ClickHouse#108350: ClickHouse#104939 (the fix for ClickHouse#23727) introduced the
empty-source REPLACE PARTITION throw-by-default; reference it so future
readers find the actual behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Jun 25, 2026
…N from empty source

When a node's random row count (random.randint(1, MAX_ROWS)) is 1, only id=0
exists, so partition 1 of `test` is empty. After MOVE PARTITION 0 TO test_dst,
`test` is empty and REPLACE PARTITION 1 FROM test reads an empty source partition.

#23727 (PR #104939) made REPLACE PARTITION from an empty source partition throw
BAD_ARGUMENTS by default, gated by allow_replace_partition_from_empty_source. That
PR updated the affected stateless tests but missed this integration test, which then
failed intermittently (~0.05% of master runs across asan/tsan/msan once #104939 merged).

Pin allow_replace_partition_from_empty_source=1 on the REPLACE query to restore the
legacy no-op semantics the test relies on, matching the fix applied to the stateless
tests in #104939. The destination partition 1 is also empty here, so no data is lost.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@fm4v fm4v added the pr-backward-incompatible Pull request with backwards incompatible changes label Jun 30, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…urce

Two CI failures on PR ClickHouse#104939 (issue ClickHouse#23727 fix):

1. Style check: the new `allow_*` setting `allow_replace_partition_from_empty_source`
   must be listed in `ci/jobs/scripts/check_style/experimental_settings_ignore.txt`
   because it is a runtime safety gate, not an experimental CREATE-time setting (so
   the alternative path of adding it to `enableAllExperimentalSettings.cpp` does not
   apply). Per `ci/jobs/scripts/check_style/check_cpp.sh` line 344, the check does a
   `comm -3` between `allow_*` tokens in `src/Core/Settings.cpp` and the union of
   `enableAllExperimentalSettings.cpp` + `experimental_settings_ignore.txt`, so adding
   the setting name to the ignore file is sufficient.

2. Fast test: two pre-existing tests (`03100_lwu_39_after_replace_partition` and
   `02486_truncate_and_unexpected_parts`) intentionally exercise the
   `REPLACE PARTITION FROM <empty-source>` no-op/clear case. Under the new default of
   `allow_replace_partition_from_empty_source = false`, these now throw `BAD_ARGUMENTS`.
   Add `SETTINGS allow_replace_partition_from_empty_source = 1` to those specific
   statements (matching the approach already taken for `00626_replace_partition_from_table*`),
   with a comment explaining why the legacy behavior is opted into here. No `.reference`
   change is needed — the silent-clear semantics are unchanged.

CI bot directive:
ClickHouse#104939 (comment)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The fix relies on the SettingsChangesHistory entry for
allow_replace_partition_from_empty_source living in the 26.6 bucket with
previous_value=true, so that compatibility < 26.6 restores the legacy
silent-drop behavior. The existing test only covered the explicit
SETTINGS allow_replace_partition_from_empty_source = 1 opt-in, leaving the
compatibility path unguarded: a future move of the entry to the wrong
version bucket, or a flip of previous_value to false, would still pass the
test while silently breaking users who rely on compatibility.

Add a case that runs the empty-source REPLACE PARTITION under
SETTINGS compatibility = '26.5' and asserts the destination is cleared.
applyCompatibilitySetting reverts only changes from version blocks strictly
newer than the compatibility version (Settings.cpp: `if (version >= it->first) break;`),
so 26.5 reverts the 26.6-bucket entry to previous_value=true while 26.6 does not.
This pins both regressions the reviewer flagged.

Addresses clickhouse-gh[bot] review comment on PR ClickHouse#104939.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-replace-partition-empty-source-data-loss

Fix data loss in REPLACE PARTITION from a source with no parts (ClickHouse#23727)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…N from empty source

When a node's random row count (random.randint(1, MAX_ROWS)) is 1, only id=0
exists, so partition 1 of `test` is empty. After MOVE PARTITION 0 TO test_dst,
`test` is empty and REPLACE PARTITION 1 FROM test reads an empty source partition.

ClickHouse#23727 (PR ClickHouse#104939) made REPLACE PARTITION from an empty source partition throw
BAD_ARGUMENTS by default, gated by allow_replace_partition_from_empty_source. That
PR updated the affected stateless tests but missed this integration test, which then
failed intermittently (~0.05% of master runs across asan/tsan/msan once ClickHouse#104939 merged).

Pin allow_replace_partition_from_empty_source=1 on the REPLACE query to restore the
legacy no-op semantics the test relies on, matching the fix applied to the stateless
tests in ClickHouse#104939. The destination partition 1 is also empty here, so no data is lost.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…r change), keep ClickHouse#23727 as original issue

Per review on PR ClickHouse#108350: ClickHouse#104939 (the fix for ClickHouse#23727) introduced the
empty-source REPLACE PARTITION throw-by-default; reference it so future
readers find the actual behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-backward-incompatible Pull request with backwards incompatible changes 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.

Replacing partition with a non-existent one leads to data loss

7 participants