Skip to content

Add ALTER TABLE ... MODIFY ENGINE to change a MergeTree-family table's engine - #107585

Open
groeneai wants to merge 51 commits into
ClickHouse:masterfrom
groeneai:alter-modify-engine-107551
Open

groeneai wants to merge 51 commits into
ClickHouse:masterfrom
groeneai:alter-modify-engine-107551

Conversation

@groeneai

@groeneai groeneai commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Experimental Feature

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

Added ALTER TABLE ... MODIFY ENGINE = ...MergeTree(...) to change the engine of a MergeTree-family table in place (for example MergeTree into ReplacingMergeTree or SummingMergeTree). Gated behind the experimental setting allow_experimental_alter_modify_engine.

Description

Closes: #107551
Related: #107481

Requested by @ alexey-milovidov.

ALTER TABLE t MODIFY ENGINE = <engine> changes a MergeTree-family table's engine in place. Only the merge semantics (MergingParams) change: columns, keys and settings are kept, and data is not rewritten. Existing parts keep their merge level, so equal-key rows that an ordinary MergeTree merge had already placed in one part stay uncollapsed under the new engine; engine.mdx documents this and the rewrite workaround. Resetting the level, as #107481 does for adopted parts, depends on question 1 below.

A new MODIFY_ENGINE command rewrites the engine clause in the CREATE query; MergingParams::parseFromEngineAST validates the new merge params against the columns and final settings first, so a rejection never leaves an unloadable CREATE on disk.

Supported targets: Replacing, Summing, Aggregating, Collapsing, VersionedCollapsing, Coalescing, Graphite. A required column may be added in the same statement, before MODIFY ENGINE. Non-replicated tables only; old-syntax tables are rejected.

Because data is not rewritten, a transition is refused when existing parts could not satisfy the target's invariants: a nullable or unreadable Graphite path/time column, and VersionedCollapsing with the version column outside the sorting key.

Two questions for review:

  1. Reload-only, rather than a live swap: merging_params is read lock-free from hot paths and often bound by const reference for a whole query, and an exclusive lock cannot be taken there. An immediate swap needs either a MultiVersion merging_params or recreating the storage. Which do you prefer?
  2. The coordinated Replicated*MergeTree switch (decision 3 on the issue) is not implemented. ReplicatedMergeTreeTableMetadata already persists the merge mode, so that is the natural next step.

Tests: 04340 to 04343 and 04353 in tests/queries/0_stateless. Docs: docs/reference/statements/alter/engine.mdx.


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

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov this implements #107551 with the four decisions you gave. Two things need your call, both in the description: (1) the new merge semantics currently apply on the next table load (DETACH/ATTACH or restart), not as a live hot-swap, because merging_params is read lock-free and can't be swapped under a lock from inside ALTER, a safe immediate swap means MultiVersion or storage recreation; (2) the coordinated Replicated*MergeTree switch isn't done yet (rejected for now). cc @alesapin as MergeTree ALTER owner.

Session: cron:clickhouse-worker-slot-0:20260616-015700

@nihalzp nihalzp added the can be tested Allows running workflows for external contributors label Jun 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e2c0737]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Segmentation fault (STID: 3132-38cf) FAIL cidb
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
point_in_polygon_const_hashing #0 FAIL dashboard

AI Review

Summary

This PR adds experimental ALTER TABLE ... MODIFY ENGINE for non-replicated MergeTree-family tables by rewriting the stored ENGINE clause and validating the target engine against the post-ALTER metadata. Most of the earlier metadata-integrity gaps have been closed, but one blocker remains in the reload-only design: some data-rewriting ALTER paths still consult the live merging_params instead of the pending target engine, so they can mutate engine-special columns into states that the target engine itself would reject.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:5687, src/Storages/MergeTree/MergeTreeData.cpp:5964, src/Storages/MergeTree/MergeTreeData.cpp:6330] The pending-engine revalidation still only checks post-ALTER metadata, so data-rewriting commands that leave the column declaration intact can bypass the target engine's special-column guards before reload. A concrete case is MODIFY ENGINE = CollapsingMergeTree(sign) followed by CLEAR COLUMN sign, or the same CLEAR in the same ALTER: c.apply keeps sign present in metadata_for_check, new_merging_params.check passes, and the later special-column rejection never fires because it still keys off the live merging_params. After reload the table runs CollapsingMergeTree over rows whose sign was rewritten to the default 0; the same hole exists for pending ReplacingMergeTree(ver) / VersionedCollapsingMergeTree(sign, ver) special columns. This breaks the contract that MODIFY ENGINE should not let later ALTERs persist a state the target engine itself would refuse.
    Suggested fix: carry the pending target engine into the CLEAR COLUMN / other data-rewrite eligibility checks instead of validating only the metadata shape, or forbid those rewrites while new_engine is pending. Add a regression that rejects both a same-statement and a later pre-reload CLEAR COLUMN of the target engine's special column.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

⚠️ No coverage measurement for commit e2c0737: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_4.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 16, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 52ebe0c — bot CR fixes)

# Question Answer
a Deterministic repro? Yes. CR1: SET allow_deprecated_syntax_for_merge_tree=1; CREATE TABLE t (d Date, k UInt32, v UInt32) ENGINE = MergeTree(d, k, 8192); ALTER TABLE t MODIFY ENGINE = ReplacingMergeTree(v) — without the fix this succeeds and rewrites the engine clause to ReplacingMergeTree(v), dropping the positional key/granularity; a subsequent DETACH/ATTACH then fails with error 42 "ORDER BY or PRIMARY KEY clause is missing" (unloadable metadata). CR2-A: ALTER TABLE t MODIFY ENGINE = CollapsingMergeTree(missing) on an extended-syntax table.
b Root cause explained? CR1: the engine-clause rewrite in DatabasesCommon.cpp does storage_ast.set(storage_ast.engine, new_engine_func->clone()), replacing the whole engine ASTFunction. For old-syntax tables the date/key/granularity are positional args inside that function, and is_custom_partitioned is false so they are not on ASTStorage to be restored either, so they are silently lost. CR2-A: applyEngineModification re-validates the new MergingParams (and can throw) but ran after alterTable() had already persisted the rewritten CREATE query, so a rejection could leave an invalid engine clause on disk.
c Fix matches root cause? Yes. CR1: reject !is_custom_partitioned in the MODIFY_ENGINE block of checkAlterIsPossible, mirroring the existing MODIFY ORDER BY / TTL / SAMPLE BY guards. CR2-A: move the applyEngineModification call to before alterTable() so validation throws before anything is persisted. No symptom-masking.
d Test intent preserved / new tests added? Added a regression case to 04340_alter_modify_engine.sql: old-syntax MergeTree(d, k, 8192) MODIFY ENGINE must throw BAD_ARGUMENTS. Existing happy-path/validation cases unchanged.
e Both directions demonstrated? Yes. With fix: 04340 passes 20/20. Without the CR1 guard (rebuilt, Build ID a16c43a7): 04340 FAILs, and the old-syntax table becomes unloadable after MODIFY ENGINE (DETACH/ATTACH -> error 42), confirming the corruption the guard prevents. CR2-A: a failed MODIFY ENGINE leaves the CREATE query unchanged (MergeTree) and the table still attachable.
f Fix is general, not a narrow patch? The two affected paths are the only ones: checkAlterIsPossible (validation) and StorageMergeTree::alter (the single applyEngineModification call site, confirmed by grep). Replicated/Shared MergeTree is already rejected earlier in the same block, so no sibling path is left unguarded. The deferred live merging_params swap (open point 3) is a separate design decision, not a code path with the same bug.

Session id: cron:clickhouse-worker-slot-4:20260616-144900

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 301eedf)

# Question Answer
a Deterministic repro? Yes. SET allow_experimental_alter_modify_engine=1; CREATE TABLE t (k Tuple(UInt32,UInt32), v UInt64) ENGINE=MergeTree ORDER BY k SETTINGS allow_tuple_element_aggregation=1; ALTER TABLE t MODIFY ENGINE = SummingMergeTree; Pre-fix: ALTER succeeds, then DETACH/ATTACH t fails with NOT_IMPLEMENTED (unloadable table).
b Root cause explained? parseFromEngineAST builds MergingParams from the engine clause only and leaves allow_tuple_element_aggregation=false. MergingParams::check gates the tuple-aggregation schema constraints on that field (MergeTreeData.cpp:1746), not on the settings argument. Both MODIFY ENGINE validation sites passed the parsed default, so the constraints the reload path enforces (registerStorageMergeTree fills the field from settings) were skipped at ALTER time, so the ALTER persisted a CREATE that only fails on next load.
c Fix matches root cause? Yes. The field is now derived from the final table settings (with any in-flight MODIFY SETTING applied) before check, with the same engine-mode gating table construction uses. No assertion widened, no constraint relaxed.
d Test intent preserved / new tests added? New regression cases in 04340: (a) flag already on the table, (b) flag flipped on in the same statement (validates against the in-flight value), (c) non-aggregating target (Replacing) where the flag is ignored and the ALTER still succeeds + attaches.
e Both directions demonstrated? Yes, on Build-ID-verified debug binaries. Without fix (Build ID c10a6975): ALTER wrongly succeeds, ATTACH fails NOT_IMPLEMENTED. With fix (Build ID 12f0dd7c): ALTER rejected upfront NOT_IMPLEMENTED, no invalid metadata persisted. Full 04340 passes 10/10.
f Fix is general, not a narrow patch? allow_tuple_element_aggregation is the only MergingParams field registerStorageMergeTree derives from storage settings; every other field comes from the engine AST that parseFromEngineAST already parses, so this is the complete sibling-path scope. The derivation is factored into one helper used by both MODIFY ENGINE sites and the reload path, so the two cannot drift. Not a symptom guard: the validation now matches the reload-time check exactly.

Session id: cron:clickhouse-worker-slot-4:20260616-160600

Comment thread src/Storages/StorageMergeTree.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 228affb)

# Question Answer
a Deterministic repro? Yes. Path 1: SET allow_experimental_alter_modify_engine=1; CREATE TABLE t (k UInt32, v UInt64) ENGINE=MergeTree ORDER BY (k,v) SETTINGS allow_summing_columns_in_partition_or_order_key=1; ALTER TABLE t MODIFY ENGINE=SummingMergeTree(v); ALTER TABLE t MODIFY SETTING allow_summing_columns_in_partition_or_order_key=0; then DETACH/ATTACH. Path 2: same MODIFY ENGINE then ALTER TABLE t DROP COLUMN v;.
b Root cause explained? A reload-only MODIFY ENGINE rewrites new_engine into the persisted CREATE but leaves live merging_params at the old mode, so the pending engine lingers on live metadata. A later ALTER with no MODIFY ENGINE of its own was not re-validated against it: settings-only alters return through an earlier branch in StorageMergeTree::alter, and the special-column DROP guards read the still-old live merging_params. Either persists a CREATE the next ATTACH rejects.
c Fix matches root cause? Yes. Re-validate the pending new_engine in checkAlterIsPossible (which runs before any live or persisted metadata change), reusing the same parseFromEngineAST + setAllowTupleElementAggregationFromSettings + check against post-ALTER columns/settings that an explicit MODIFY ENGINE uses, so the gate matches the reload path. Not a symptom guard.
d Test intent preserved / new tests added? Added 04340 cases (d) settings flip invalidating the pending engine rejected + table still loadable, (e) DROP of the pending summing column rejected before live metadata changes, (f) unrelated later ALTER on a pending engine still works. No existing assertions weakened.
e Both directions demonstrated? Yes. Without fix (Build ID 12f0dd7cd620): path 1 bricks the table (ATTACH Code 36). With fix (Build ID 0d4b70c677a4): both rejected upfront, live CREATE intact, ATTACH OK. 04340 passes 20/20 no-random and 10/10 with randomization.
f Fix is general, not a narrow patch? Yes. new_engine is the only reload-deferred metadata field and applyEngineModification the only deferred-swap point, so re-validating the pending engine in the pre-flight gate covers the entire divergence class (any later column or setting alter), not just the two reported cases.

The live hot-swap vs reload-only design (open point 3) is unchanged and remains for the maintainer call.

Session id: cron:clickhouse-worker-slot-0:20260616-172600

Comment thread src/Storages/MergeTree/MergeTreeData.h Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE TABLE g (k UInt32, v UInt64, PROJECTION p (SELECT k, sum(v) GROUP BY k)) ENGINE=MergeTree ORDER BY k; SET allow_experimental_alter_modify_engine=1; ALTER TABLE g MODIFY ENGINE = ReplacingMergeTree; On the unfixed binary this ALTER always succeeds and persists a special-mode + projection CREATE that a fresh CREATE TABLE rejects (Code 344).
b Root cause explained? The reload-only design leaves the live merging_params at Ordinary, so the live ADD PROJECTION guard never fires, and the pending-engine validation in checkAlterIsPossible replicated MergingParams::check and the tuple gate but not the registerStorageMergeTree projection check (hasProjections() && mode != Ordinary && deduplicate_merge_projection_mode == THROW). So a special-mode switch with projections present bypassed the rule that CREATE enforces.
c Fix matches root cause? Yes. The same projection + deduplicate_merge_projection_mode check is added inside the existing engines_to_validate loop, against metadata_for_check (carries any ADD PROJECTION from this ALTER) and settings_for_check, before any live or persisted metadata change. No symptom guard.
d Test intent preserved / new tests added? Yes. 04340_alter_modify_engine gains cases (g)-(j): existing projection + MODIFY ENGINE to special -> rejected; ADD PROJECTION + MODIFY ENGINE in one statement -> rejected; pending special engine + later ADD PROJECTION -> rejected; deduplicate_merge_projection_mode = rebuild -> allowed. Existing assertions unchanged.
e Both directions demonstrated? Yes. Without fix (Build ID d9157f4b7c6d): ALTER wrongly succeeds, persists a CREATE that fresh CREATE TABLE rejects (Code 344). With fix (Build ID 5f8a89f93635): ALTER rejected up front, table untouched and loadable; rebuild mode still allowed. Full test 10/10 + 10/10 (no-random and randomized).
f Fix is general, not a narrow patch? Yes. Gate-f audit: the construction-time rejections gated on (mode, settings) are engine-arg parsing (handled by parseFromEngineAST), tuple-aggregation (fixed in 301eedf), and projections + throw (this fix). Projections was the last missing one. The single check covers explicit and pending engines and same/later-statement projections; the live guard covers already-live special modes. CR-B is a doc-only change (the body comment was already accurate; the header decl and AlterCommands.cpp comments were stale).

Session id: cron:clickhouse-worker-slot-1:20260616-185300

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (k UInt32, v UInt64) ENGINE = MergeTree ORDER BY (k, v) SETTINGS allow_summing_columns_in_partition_or_order_key = 1; ALTER TABLE t MODIFY ENGINE = SummingMergeTree(v); ALTER TABLE t RESET SETTING allow_summing_columns_in_partition_or_order_key; -> without fix the reset is accepted and the next ATTACH fails Code 36 every time.
b Root cause explained? checkAlterIsPossible built the candidate MergeTreeSettings as getSettings(settings_changes) = current live settings + in-flight changes. changeSettings and reload build them as getDefaultSettings() + final settings_changes. RESET SETTING removes the setting from settings_changes, so the delta-on-current keeps the old value (1) and validation passes, but reload reverts it to the default (0) -> the persisted SummingMergeTree(v) CREATE is rejected on next load.
c Fix matches root cause? Yes. Build the candidate settings from getDefaultSettings() + final metadata_for_check.settings_changes, exactly as changeSettings/reload do, so validation and reload agree. No symptom guard.
d Test intent preserved / new tests added? Added cases (k) separate-statement RESET SETTING and (l) same-statement MODIFY ENGINE ..., RESET SETTING ... to 04340_alter_modify_engine; both assert upfront rejection + table stays loadable. Existing cases unchanged.
e Both directions demonstrated? Yes, Build-ID-verified. Without fix (5f8a89f93635): reset accepted, ATTACH fails Code 36; full 04340 fails on the new case. With fix (52d1231aa07a): rejected up front, table loadable; 04340 passes 160/160 runs.
f Fix is general, not a narrow patch? The current-settings-plus-delta mistake existed only at this one site; the sibling validation in applyEngineModification already used *getSettings() after changeSettings, so it was correct. The fix makes both engine-validation paths build settings the same way reload does, covering MODIFY SETTING and RESET SETTING symmetrically.

Session id: cron:clickhouse-worker-slot-1:20260616-202500

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (TABLE ENGINE access fix, 9b8702b)

# Question Answer
a Deterministic repro? Yes. With access_control_improvements.table_engines_require_grant = 1: a user GRANTed only ALTER ORDER BY runs ALTER TABLE t MODIFY ENGINE = ReplacingMergeTree and it succeeds, when CREATE of the same engine would be denied. New test 04341_alter_modify_engine_access reproduces it on demand.
b Root cause explained? getRequiredAccessForCommand emitted only ALTER_ORDER_BY for MODIFY_ENGINE. CREATE TABLE additionally enforces AccessType::TABLE_ENGINE on the engine name (InterpreterCreateQuery::getRequiredAccess). MODIFY ENGINE persists the engine into the CREATE query, so omitting the TABLE_ENGINE requirement lets a user install an engine they are not granted to create.
c Fix matches root cause? Yes. The MODIFY_ENGINE branch now adds AccessType::TABLE_ENGINE on command.engine->as<ASTFunction &>().name, a direct mirror of the CREATE contract, in addition to the structural alter privilege. No symptom guard.
d Test intent preserved / new tests added? New test 04341_alter_modify_engine_access added (denied without the grant, allowed with it, reloads as ReplacingMergeTree). Existing 04340 unchanged and still passing.
e Both directions demonstrated? Yes, Build-ID-verified. WITHOUT fix (Build ID 52d1231aa07a): the alter is wrongly allowed, test FAILS (denial line missing). WITH fix (Build ID 4fc9ee70faec): denied without the grant, allowed with it; 04341 passes 10/10, 04340 + 04341 pass 3/3 each.
f Fix is general, not a narrow patch? MODIFY ENGINE is the only ALTER command that installs a table engine (parser sets command.engine only for MODIFY_ENGINE); other commands do not need TABLE_ENGINE. The grant key is the engine name only (no db/table), matching CREATE. The check is unconditional and no-ops via the access layer when the setting is off, like CREATE.

Session id: cron:clickhouse-worker-slot-0:20260617-030200

Comment thread src/Storages/MergeTree/MergeTreeData.h Resolved
@groeneai
groeneai force-pushed the alter-modify-engine-107551 branch from 9b8702b to 1140974 Compare June 20, 2026 07:37
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1140974

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
CH Inc sync — CH Inc sync (private, not actionable)

No failed tests on this SHA. Finish Workflow + Mergeable Check + PR all pass.

Session id: cron:our-pr-ci-monitor:20260702-163000

@groeneai
groeneai force-pushed the alter-modify-engine-107551 branch 2 times, most recently from f3eab9b to 0b3fa52 Compare July 4, 2026 12:17
@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0b3fa52

CI fully finished on this head (Finish Workflow completed 2026-07-04T16:26:47Z, 0 checks queued/in_progress). Every failure has an owner.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) :: 04056_npy_large_shape_validation infra: macOS runner ModuleNotFoundError: No module named 'numpy' (not PR-caused; not in this PR's diff; 53 hits / 20 PRs / 0 master) a fix task is moved to pending (missing Python modules on arm_darwin runner — fixing PR link to follow here)
Fast test (arm_darwin) :: 03321_forwarded_for infra: macOS runner Python-env import failure (pure_http_client), same class (21 hits / 19 PRs / 0 master; not PR-caused) a fix task is moved to pending (same arm_darwin runner Python-env issue — fixing PR link to follow here)
Stress test (arm_msan) :: Block structure mismatch STID 0993-386d trunk fuzzer bug (44 hits / 37 PRs / 0 master in 30d; not PR-caused) tracked in the 0993-386d JoinStep-duplicate-column fix task

None of the failing tests are in this PR's diff (the PR adds ALTER TABLE ... MODIFY ENGINE: parser + storage + settings + docs + 04340/04341 tests). The arm_darwin failures are the known macOS-runner missing-Python-module class; the arm_msan failure is the chronic JoinStep block-mismatch trunk fuzzer bug.

Session id: cron:our-pr-ci-monitor:20260704-170000

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to the two arm_darwin lines above: they have a merged fixing PR, so they link directly (the "fix task moved to pending" wording was imprecise):

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) :: 04056_npy_large_shape_validation infra: macOS-runner missing numpy #108859 (v72 runner bootstrap, merged 2026-07-03) — drain-tail confined to one stuck straggler host (ip-172-31-7-14, ap-southeast-2), 0 master
Fast test (arm_darwin) :: 03321_forwarded_for infra: macOS-runner missing pandas, same class #108859 (merged) — same straggler host

Session id: cron:our-pr-ci-monitor:20260704-170000

groeneai and others added 5 commits July 8, 2026 11:19
…use#107551)

Add a new DDL to change a MergeTree-family table's engine in place, e.g.
plain MergeTree -> ReplacingMergeTree / SummingMergeTree / CollapsingMergeTree /
VersionedCollapsingMergeTree / AggregatingMergeTree / GraphiteMergeTree. Only the
merge semantics (MergingParams) change; ORDER BY / PARTITION BY / PRIMARY KEY /
SAMPLE BY / columns are untouched.

Syntax: ALTER TABLE t MODIFY ENGINE = ReplacingMergeTree(version). A required
column for the target engine (Collapsing sign, VersionedCollapsing sign+version)
may be added in the same statement, before the MODIFY ENGINE command:
  ALTER TABLE t ADD COLUMN sign Int8, MODIFY ENGINE = CollapsingMergeTree(sign).

Gated behind the experimental setting allow_experimental_alter_modify_engine.
The new engine must be the same replication kind and a MergeTree-family engine;
the resulting MergingParams is validated against the columns.

The new ENGINE clause is persisted into the table's CREATE query; the new merge
semantics take effect when the storage is next constructed (DETACH/ATTACH or
restart). A safe immediate live swap of the read-lock-free merging_params (via
MultiVersion or storage recreation) and the coordinated Replicated*MergeTree path
are follow-ups; Replicated tables are rejected for now.

Reuses the part-level-reset rationale of ClickHouse#107481 conceptually (existing parts keep
their data and re-merge under the new semantics on FINAL/OPTIMIZE).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
04340_alter_modify_engine: experimental gate, MergeTree -> Replacing/Summing,
single-statement ADD COLUMN + MODIFY ENGINE -> Collapsing, FINAL dedup/sum after
reload, and validation errors (non-MergeTree target, missing required column).

Docs: new alter/engine.md page documenting MODIFY ENGINE, linked from the ALTER
index.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…l settings ignore list

The Style check (check_cpp.sh) requires every allow_* setting in
Settings.cpp to appear in either enableAllExperimentalSettings.cpp or
experimental_settings_ignore.txt. allow_experimental_alter_modify_engine
gates an ALTER (not a CREATE) operation, so it belongs in the ignore list
alongside the sibling allow_experimental_alter_materialized_view_structure
gate, rather than in enableAllExperimentalSettings (which only enables
features for CREATE-query replica recovery).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ting

Two correctness fixes on the MODIFY ENGINE path.

Reject old-syntax MergeTree tables. A table created as MergeTree(date, key,
8192) keeps the sorting/sampling key and granularity as positional arguments
inside the engine ASTFunction. The engine-clause rewrite replaces the whole
function, dropping those arguments; is_custom_partitioned is false for such
tables, so the key is not restored from ASTStorage either. The result was an
ENGINE = ReplacingMergeTree(v) clause with no ORDER BY, unloadable on the next
ATTACH (error 42). Reject these in checkAlterIsPossible, as MODIFY ORDER BY /
TTL / SAMPLE BY already do.

Validate the new MergingParams before persisting. applyEngineModification
re-checks the candidate MergingParams and can throw; it ran after alterTable()
had already written the rewritten CREATE query, so a rejection could leave an
invalid engine clause on disk. Move the call before alterTable().

The deferred live merging_params swap (open point 3) is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ing test

Pre-persist MergingParams validation used the current MergeTreeSettings, not
the settings after a MODIFY SETTING in the same ALTER. Switching to a Summing
or Coalescing engine that needs allow_summing_columns_in_partition_or_order_key
(or the coalescing variant) was checked against the old flag, so MODIFY ENGINE
combined with MODIFY SETTING in one statement was wrongly rejected, and the
check disagreed with the reload path. Build the candidate settings from the
in-flight setting changes (getSettings with the metadata's settings_changes).

Test: select v directly under FINAL instead of sum(v) for the SummingMergeTree
case. sum(v) returns the same result whether or not the engine changed; reading
the merged rows fails if the rewrite is absent (plain MergeTree rejects FINAL).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The MODIFY ENGINE Graphite path guard has separate isVariant, isDynamic and
isObject terms, and the documentation promises all three rejections, but the
test file covered only Array, Tuple, Map, QBit and the LowCardinality wrappers.
Deleting any one of the three guards left the suite green.

The three terms are distinct TypeIndex tests, so no other term of the condition
can cover them. Verified by deleting all three: exactly the three new cases fail
with "query succeeded but the server error 36 was expected", one per guard, and
restoring the guards returns the binary to its previous build id.

The JSON case must insert a valid JSON literal; a bare string fails earlier at
INSERT with Code 117 and the case would never reach the guard.
checkAlterIsPossible replays the ALTER's other commands onto a copy of the
current metadata to validate the target engine against the columns this same
statement produces. It applied them to unnormalized columns, while the real
preparation and commit paths call removeImplicitStatistics first.

auto_statistics_types defaults to 'basic, uniq_v2', so every column carries an
implicit basic statistic. Adding an explicit statistic of the same type in a
statement that also changes the engine then hit the duplicate-type check in
ColumnStatisticsDescription::merge and a valid command was rejected:

  CREATE TABLE t (a UInt32, k UInt32) ENGINE = MergeTree ORDER BY a
      SETTINGS auto_statistics_types = 'basic';
  ALTER TABLE t MODIFY ENGINE = ReplacingMergeTree, ADD STATISTICS k TYPE basic;
  -- Code: 708. Statistics type name Basic has existed in column k

The same ADD STATISTICS without MODIFY ENGINE succeeded, so only the replay was
affected; a genuine duplicate is still rejected.

Found by the second-model review of the master merge.
@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature and removed pr-feature Pull request with new product feature labels Aug 14, 2026
Five graphite arms of 04340_alter_modify_engine read back the rolled-up `Time`
value. The `graphite_rollup` config CI installs has a second retention with
precision 6000, and above precision 900 GraphiteRollupSortedAlgorithm rounds
relative to the local day rather than to the raw timestamp, so the rounded
value depends on the server time zone. CI randomizes the server time zone
(ClickHouseProc.set_random_timezone rewrites /etc/localtime), and the merge
thread has no query context, so DateLUT::instance() resolves to that zone. The
Enum16 arm additionally reddened hard: under Europe/Paris the rounded value is
-3600, which the enum cannot name, giving Code 691 UNKNOWN_ELEMENT_OF_ENUM.

Assert the row collapse and the surviving version instead, which are the
properties these arms exist to check and which hold in every time zone. A
mutation of the expected count still reddens each arm, so the coverage is
preserved. `session_timezone` is not a usable pin here: it is a session-level
setting and the background merge does not read it.

Verified against 599 time zones by model and end-to-end under UTC,
Europe/Paris, America/Los_Angeles, Asia/Kolkata, Australia/Eucla,
America/St_Johns, Pacific/Kiritimati and Africa/Khartoum. Before this change
the test passes only under UTC. Plain `CREATE TABLE ... GraphiteMergeTree`
rounds identically, so the rounding itself is the engine's existing behaviour
and not something MODIFY ENGINE introduces.
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

…e Graphite arms

The flaky check reported "Test runs too long (> 180s)" for 04340_alter_modify_engine. Across all
250 runs on this head the test sat at a 146s median with a 177.9s passing maximum, i.e. 2.1s of
headroom against the cap, so the tail crossed the line whenever the runner was loaded.

The cost driver is async_insert, not the data volume. Every INSERT in the test writes a single row
and then the next statement asserts what the merge produced, so with async inserts enabled each of
the ~60 INSERTs blocks on the async buffer flush instead of doing work. Measured locally with
otherwise identical settings, the pre-split file ran at a 1.33s median with async_insert=0 against
a 10.76s median and a 35.01s maximum with async_insert=1.

Pin async_insert = 0 in the test body, which beats the runner's injected value, rather than using
the blanket no-async-insert tag. The test asserts merge outcomes and never exercises the async
insert path, so nothing is lost.

Also split the Graphite and special-mode arms into 04353_alter_modify_engine_graphite. The two
halves are independent: every SET in the moved range is already paired inside it and no table
crosses the seam. The union of the two reference files is the same multiset of lines as the
original, and each half is an ordered subsequence of it, so no assertion changed.

After both changes, 50 runs at 16 workers with fully randomized settings give a 0.68s median /
0.98s maximum for 04340 and a 1.33s median / 1.44s maximum for 04353. Forcing async_insert=1
keeps the maximum at 1.63s. Corrupting one reference line in either half still fails the test.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ef48adc

CI is fully finished on this head and there are no failures to own.

Gates: no check queued/in_progress/pending; Config Workflow = success, Finish Workflow = success (2026-08-15T06:48:49Z); >20 min elapsed for CIDB ingestion.

Coverage verified from the praktika report rather than the skip ratio: result_pr.json top-level OK, 177 leaves, 158 OK / 19 SKIPPED / 0 DROPPED. Every skip carries a real reason (6 not labelled pr-performance, 5 not a bug-fix PR, 3 reused from cache, 2 not labelled ci-toolchain, 1 no failed tests from previous runs, 1 no integration-test updates, 1 no src/Coordination changes). CIDB has zero FAIL/ERROR rows at this SHA.

Check / test Reason Owner / fixing PR
(none) - -

Session id: cron:our-pr-ci-monitor:20260815-070000

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This change adds the experimental ALTER TABLE ... MODIFY ENGINE statement (new parser keyword, AST node, alter-command handling, and CREATE-query metadata rewrite), all behind a setting that defaults off. It touches no query-execution code, so it cannot plausibly move a ClickBench SELECT. The only flagged query, clickbench Q18 (+5.0%), shows flat CPU time (+0.8%) and mixed/borderline test signals, so it is downgraded to not_sure as run-to-run variance rather than a PR effect.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1062 1116 +5.0% <0.0001 This PR only adds the experimental ALTER TABLE ... MODIFY ENGINE DDL path (parser/AST/metadata rewrite, gated off by default); it cannot touch a ClickBench SELECT's execution. CPU time is flat (+0.8%), so the +5.0% wall-time move is run-to-run variance.

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: 14e7ede9-cddd-4c11-bb89-151b1607182d
  • MIRAI run: 1f009680-556a-4582-bad8-d7a1ed284d64
  • PR check IDs:
    • clickbench_156106_1787549151
    • clickbench_156120_1787549151
    • clickbench_156126_1787549151
    • tpch_adapted_1_official_156137_1787549151
    • tpch_adapted_1_official_156162_1787549151
    • tpch_adapted_1_official_156176_1787549151

…dify-engine-107551

One conflict, in src/Core/Settings.cpp. Master obsoleted
allow_experimental_codecs (it is now MAKE_OBSOLETE) and put
enable_alp_codec, enable_quantized_codec, enable_sz3_codec and
enable_zxc_codec at that position, which is exactly where this branch had
inserted allow_experimental_alter_modify_engine just above it.

Resolved by keeping both sides: allow_experimental_alter_modify_engine
stays directly after allow_experimental_unique_key, master's four codec
settings follow it, and the obsoleted allow_experimental_codecs DECLARE
is not restored (restoring it would both revert the obsoletion and
duplicate the name).
…block

Master opened the 26.9 settings-history block while this branch was behind,
so the merge left this branch's entry sitting in the 26.8 block.
check_settings_changes_history in ci/jobs/check_style.py requires every
setting touched by a change that also edits src/ to be recorded under the
block matching cmake/autogenerated_versions.txt, which is now 26.9.

26.8 was released without this setting, so a record there would also tell
`compatibility` that the setting changed in a release that never had it.
The entry text is unchanged; only the block it sits in.
Master turned docs/reference/statements/alter/index.mdx into generated
output while this branch was behind: the file gained
{/*AUTOGENERATED_START*/} / {/*AUTOGENERATED_END*/} markers, and this
branch's hand-written `ENGINE` row now sits inside that region. The
Mintlify docs job rejects any change to a marked region
(ci/jobs/docs_job_mintlify.py calls check_autogenerated_regions), so the
row has to come from the generator's source data instead.

The row now lives in the `ALTER` statement description in
registerStatementAlter, which is what the generator renders into that
region, so the nightly documentation run emits it. Reverting the .mdx
alone would have dropped the row at the next regeneration.
The recent master merge left `#include <Parsers/ASTIdentifier.h>` in the file
twice: master had gained the include independently while this branch already
carried one, and the resolution kept both sides. `Build (arm_tidy)` runs
readability-duplicate-include with `WarningsAsErrors: '*'`, so this was the
only error in that job, and it suppressed every downstream check on the tree.

Dropping the copy this branch added leaves the include block byte-identical
to master. The header is `#pragma once`, so the translation unit is
unchanged, and `getIdentifierName` in the new code is still served by
master's own include, which master needs for `ASTTableIdentifier`.
groeneai and others added 2 commits September 3, 2026 20:31
`FINAL` and the merge algorithms treat a part above level zero as already
merged by the current engine: `IMergingAlgorithmWithDelayedChunk` and
`IMergingAlgorithmWithSharedChunks` both short-circuit
`rowsHaveDifferentSortColumns` when two rows come from the same source at a
non-zero level. `MODIFY ENGINE` leaves existing parts at their old level, so
rows with equal sorting keys that an ordinary `MergeTree` merge had already
placed in one part survive the change.

Measured on a debug build for all five collapsing targets, after
`OPTIMIZE TABLE ... FINAL` on a plain `MergeTree` and a reload:
`ReplacingMergeTree` keeps 2 rows of 1, `SummingMergeTree` and
`AggregatingMergeTree` keep 10 and 20 instead of 30, `CoalescingMergeTree`
keeps 7 and `NULL`, `CollapsingMergeTree` keeps both signs. A later
`OPTIMIZE TABLE ... FINAL` does not repair it.

The page claimed the opposite. State the actual behaviour and the rewrite
workaround; the claim can be restored when the part-level handling lands.
That remains a metadata and timing design call, open in the review thread on
`MergeTreeData.h` together with the engine swap mechanism.

Co-Authored-By: Claude Opus 5 <[email protected]>
…he other flags

`MODIFY ENGINE` added an `engine` pointer to `ASTAlterCommand`, which took the
class from 512 to 520 bytes. 512 is a jemalloc size class boundary, so the
allocation for every `ASTAlterCommand` the parser builds rounded up to the next
class, 640, costing 128 extra bytes on the AST of every `ALTER` query rather than
only on `MODIFY ENGINE` ones.

`Parser memory check` reported this on ten plain `ADD COLUMN`, `DROP COLUMN`,
`MODIFY COLUMN` and `COMMENT COLUMN` queries, each a constant 128 bytes over
master at 9.2% to 11.5%, above its 100 byte and 1.0% thresholds.

`replace` was declared alone between two `String` members, so it occupied an
eight byte slot of which seven bytes were padding. Declaring it next to the other
flags places it in the existing padding after `move_destination_type` and returns
the class to 512, making the allocation identical to master again. The member is
only read by name and its JSON serialization is keyed by name, so the move does
not change behaviour.

Measured with a `sizeof` probe on the header and independently with `gdb` on the
built binary: 520 before, 512 after, and 512 on master.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107585&sha=3f235cce207cf3c355ff3e44bc6e454ea0a80fa7&name_0=PR&name_1=Parser%20memory%20check
ClickHouse#107585
@abashkeev abashkeev added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d056a20

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_asan_ubsan, azure, sequential) / 04340_distributed_plan_status_reenqueue_fault flaky: the injected recordFailure marker never appears, so the test prints reenqueue fault handled: 0. Breadth over 30 days: 30 distinct PRs and 8 true-master runs #118417 (external, open) plus #105942 (external, open) for the leaked-failpoint half
Stateless tests (arm_asan_ubsan, azure, sequential) / 04648_distributed_plan_task_error_propagation master regression with a hard onset on 2026-09-06: the recorded CANNOT_SCHEDULE_TASK is lost and the client sees POCO_EXCEPTION code 1000 instead. Breadth over 30 days: 37 distinct PRs and 12 true-master runs #118417 (external, open) and #118390 (mine, open)
Build profile diff infra: the job exits 1 before any comparison, on Code: 497 ACCESS_DENIED for default.binary_sizes in the CI logs cluster (has_pr_data, build_profile_diff_job.py:721); reproduced on unrelated PRs by other authors a fix task is created (investigating at full effort, fixing PR link to follow here)
CH Inc sync reported a failure in the private mirror CH Inc sync (private, not actionable by me)

PR is the workflow rollup and is red only because of the rows above. Coverage: 150 of 174 checks
passed, 20 skipped, 0 dropped, nothing queued; Config Workflow, Fast test, Style check (0/15),
Finish Workflow and Mergeable Check are all green. The two stateless failures are the same pair,
in the same job flavour, that failed on an unrelated PR of mine in the same window, so neither is
reachable from this diff.

Session id: cron:our-pr-ci-monitor:20260907-213102

bool share_nested_offsets = (*getSettings())[MergeTreeSetting::share_nested_offsets];
/// Replay needs normalized columns: an implicit statistic collides with an explicit one of the same type.
removeImplicitStatistics(metadata_for_check.columns);
for (const auto & c : commands)

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.

This pending-engine revalidation still only sees post-ALTER metadata, so it misses data-rewriting commands that are supposed to stay forbidden once the target engine is pending. A concrete path is ALTER TABLE t MODIFY ENGINE = CollapsingMergeTree(sign), then before reload ALTER TABLE t CLEAR COLUMN sign IN PARTITION ...: c.apply leaves sign present in metadata_for_check, new_merging_params.check passes, and the later checkAlterEligibility guard never fires because the live merging_params is still Ordinary until reload. After the reload the table runs CollapsingMergeTree over rows whose sign column was rewritten to the default 0, a mutation that the live CollapsingMergeTree path explicitly rejects. The same bypass applies to pending ReplacingMergeTree(ver) / VersionedCollapsingMergeTree(sign, ver) special columns. Please carry the pending engine into the special-column CLEAR / data-rewrite checks as well, or reject those alters while new_engine is still pending.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov, this is question 1 in the description, with new measurements.

Between MODIFY ENGINE and the next table load, the table still runs as its old engine, so the target engine's guards on its special columns do not apply yet. Measured on dd56a3e0 with MODIFY ENGINE = CollapsingMergeTree(sign) pending: CLEAR COLUMN sign, ALTER UPDATE sign = 0 and an INSERT with sign = 0 are all accepted, and after DETACH/ATTACH SELECT ... FINAL returns 1 row of 5. With ReplacingMergeTree(ver) pending, CLEAR COLUMN ver is accepted and FINAL then returns the older version. A live table with the target engine refuses each of these. Found from #107585 (comment).

Each of these guards reads the live merging_params, and more of them keep turning up, so I do not think adding them one by one converges. Options:

  1. Recreate the storage at the end of the ALTER, so the new engine applies at once and the existing guards cover it unchanged.
  2. Keep reload-only, and refuse data-rewriting ALTERs, mutations and lightweight updates while a change is pending. INSERT would still be unguarded.
  3. Keep reload-only and add the guards one by one.

I would do 1. Which do you prefer?

@groeneai

groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - dd56a3e

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
Performance Comparison (arm_release, master_head, 2/6) / read_in_reverse_order_final #0 dashboard confirmed_regression, client_time 0.0063 -> 0.0099 s (+56.1%), which the shard's own report calls only unstable. The fixture reads a ReplacingMergeTree with FINAL ORDER BY x DESC LIMIT 10, and since #122073 the harness stops merges right after the fill, so each server measures a different number of parts. It issues no ALTER, and this diff adds ALTER ... MODIFY ENGINE handling without touching the FINAL read path. In the last 7 days the same query was reported slower on 13 other pull requests and unstable on 91, true master included. The tree this job built (dd56a3e0 merged into master f369f769) is 2 commits older than the fix, and the fix's part-count guard is absent there #122335 (mine, merged). The next master merge picks it up: the current head is a maintainer's own master merge, so I am not pushing another one on top of it now
Mergeable Check, PR rollups, red only because of the row above #122335 (mine, merged)
Sync - CH Inc sync (private, not actionable by me)

All 173 check runs completed (153 pass, 19 not selected, 1 red) and Finish Workflow is green.
CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260926-120120

…-107551

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

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

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-unknown PR origin: unclassified (legacy task) manual approve Manual approve required to run CI pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ALTER TABLE ... ENGINE = ...MergeTree

4 participants