Skip to content

Fix settings-only ALTER on MergeTree with SimpleAggregateFunction in ORDER BY - #105111

Merged
azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-104463-alter-settings-simple-aggregate
Jul 13, 2026
Merged

azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-104463-alter-settings-simple-aggregate

Conversation

@groeneai

@groeneai groeneai commented May 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #104463

StorageMergeTree::alter and StorageReplicatedMergeTree::alter re-ran verifySortingKey on almost every ALTER when allow_suspicious_primary_key was off, so unrelated ALTERs (settings, comments, codecs, adding a non-key column, ...) failed with DATA_TYPE_CANNOT_BE_USED_IN_KEY on tables created with allow_suspicious_primary_key = 1. The check now runs only when the resolved sorting key actually changed (MergeTreeData::sortingKeyChanged, comparing key column names and data-type names), in the same place in both engines.

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):

Fix an unexpected DATA_TYPE_CANNOT_BE_USED_IN_KEY error on ALTER queries that cannot change the sorting key (settings, comments, codecs, adding a non-key column, etc.) for MergeTree tables that have a SimpleAggregateFunction (or another type allowed only with allow_suspicious_primary_key = 1) in the sorting key.

Version info

  • Merged into: 26.7.1.850 (included in 26.7 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @alesapin @CurtizJ @KochetovNicolai — could you review? Small fix in StorageMergeTree::alter: moves the verifySortingKey check to after the settings-only / comment-only early returns to match StorageReplicatedMergeTree::alter. Closes #104463 (raised by @azat via @clickgapai). Stateless regression test included; verified failing without the fix and 50/50 passing with the fix locally.

session: cron:clickhouse-ci-task-worker:20260516-100000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (worker)

(a) Deterministic repro? Yes — running the exact ALTER TABLE t MODIFY SETTING index_granularity = 8192; from the issue against an unmodified build reliably triggers Code: 549 DATA_TYPE_CANNOT_BE_USED_IN_KEY.

(b) Root cause explained? StorageMergeTree::alter invoked MergeTreeData::verifySortingKey unconditionally before the if (commands.isSettingsAlter()) ... else if (commands.isCommentAlter()) ... else ... chain. For tables originally created with allow_suspicious_primary_key = 1 but altered in a session that has it disabled, that verification rejected the new metadata's sorting key even though the ALTER does not touch the key. StorageReplicatedMergeTree::alter calls verifySortingKey only after the settings/comment early returns, so the two engines were inconsistent.

(c) Fix matches root cause? Yes — the verifySortingKey call is moved into the else branch (i.e. only when the ALTER is neither settings-only nor comment-only). This is the exact position StorageReplicatedMergeTree::alter uses, and AlterCommand::isSettingsAlter/isCommentAlter only return true for MODIFY_SETTING/RESET_SETTING/COMMENT_* commands which cannot change the sorting key.

(d) Test intent preserved / new tests added? Existing tests are untouched. A new stateless test 04248_104463_alter_settings_simple_aggregate_func_order_by covers MODIFY SETTING, RESET SETTING, MODIFY COMMENT, COMMENT COLUMN succeeding; ADD COLUMN still rejected with DATA_TYPE_CANNOT_BE_USED_IN_KEY; and ADD COLUMN succeeding once allow_suspicious_primary_key = 1 is re-enabled — locking in both directions of the behavior.

(e) Both directions demonstrated? Yes. Locally, on a debug build of the patched branch with the fix reverted (via git stash) the new test fails immediately on the first MODIFY SETTING; with the fix restored the test passes 50/50 with full randomization.

(f) Fix is general, not a narrow patch? verifySortingKey has only two ALTER call sites in the codebase (StorageMergeTree::alter, StorageReplicatedMergeTree::alter) and they now agree. CREATE/ATTACH call sites in registerStorageMergeTree.cpp are unrelated and not affected. No defensive nullptr/early-return guards were introduced — the call simply moved to where it semantically belongs.

session: cron:clickhouse-ci-task-worker:20260516-100000

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

clickhouse-gh Bot commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0783b1c]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
codecs_int_insert #12::old FAIL query history
codecs_int_insert #12::new FAIL query history
file_table_function #18::old FAIL query history
file_table_function #18::new FAIL query history
file_table_function #21::old FAIL query history
file_table_function #21::new FAIL query history
number_formatting_formats #2::old FAIL query history
number_formatting_formats #2::new FAIL query history
number_formatting_formats #6::old FAIL query history
number_formatting_formats #6::new FAIL query history
8 more test cases not shown

AI Review

Summary

This PR narrows verifySortingKey so it runs only when the resolved sorting key actually changes, which fixes the spurious DATA_TYPE_CANNOT_BE_USED_IN_KEY exception on grandfathered SimpleAggregateFunction keys during metadata-only ALTERs. I reviewed the current squashed head commit, the full prior thread history, and the remaining parser/key-comparison edge cases, and I did not find any remaining blocking or major issues.

Final Verdict

✅ No new findings. The current change looks correct to merge.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 16, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed commit 52c3849 addressing the mixed-command gap flagged by clickhouse-gh[bot].

Bot's concern, restated

AlterCommands::isSettingsAlter and AlterCommands::isCommentAlter are both all_of checks per individual command. A mixed statement like

ALTER TABLE t MODIFY COMMENT 'x', MODIFY SETTING merge_with_ttl_timeout = 60;

contains commands that satisfy one predicate each but not both, so both helpers return false. The mixed shape then fell through to the trailing else branch in StorageMergeTree::alter and still ran MergeTreeData::verifySortingKey, re-introducing the DATA_TYPE_CANNOT_BE_USED_IN_KEY exception that the original PR was meant to remove. The pure-settings / pure-comment branches were correctly skipping the check; the bot is right that the all_of predicates don't compose for mixed statements.

(Note: MODIFY SETTING greedily consumes a comma-separated setting list, so the bot's example syntax MODIFY SETTING X = Y, MODIFY COMMENT 'z' raises a parser error in 26.5 — but the equivalent shape MODIFY COMMENT 'z', MODIFY SETTING X = Y parses fine and exhibits the bug.)

Fix

Added a dedicated else if (commands.areNonReplicatedAlterCommands()) branch (using the existing helper which is all_of (isSettingsAlter || isCommentAlter)) in StorageMergeTree::alter. The same gap exists by symmetry in StorageReplicatedMergeTree::alter, so the equivalent branch was added there as well. Both branches perform changeSettings + setInMemoryMetadata + alterTable and skip verifySortingKey. Statements that mix in a sorting-key-relevant subcommand (e.g. ADD COLUMN) still fail areNonReplicatedAlterCommands and fall through to the unchanged key-verifying branch.

Tests

Extended tests/queries/0_stateless/04248_104463_alter_settings_simple_aggregate_func_order_by.sql with:

  • MODIFY COMMENT 'x', MODIFY SETTING merge_with_ttl_timeout = 60 (must pass on both MergeTree and AggregatingMergeTree)
  • COMMENT COLUMN value 'x', MODIFY SETTING merge_with_ttl_timeout = 45 (must pass)
  • MODIFY COMMENT 'x', RESET SETTING merge_with_ttl_timeout (must pass)
  • MODIFY COMMENT 'cmt', ADD COLUMN extra2 Int (must still throw DATA_TYPE_CANNOT_BE_USED_IN_KEY — guards against the new branch eating sorting-key-relevant ALTERs)

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes — temporarily reverted just the StorageMergeTree.cpp branch, rebuilt, ran ALTER TABLE t_mt MODIFY COMMENT 'no-fix should fail', MODIFY SETTING merge_with_ttl_timeout = 100, got Code: 549. DATA_TYPE_CANNOT_BE_USED_IN_KEY. Same query passes once the branch is restored.
b Root cause explained? commands.isSettingsAlter() and commands.isCommentAlter() are all_of predicates per individual command. A mixed statement satisfies neither, falls into the else branch, runs verifySortingKey, which throws on the suspicious SimpleAggregateFunction key.
c Fix matches root cause? Adds a branch keyed on areNonReplicatedAlterCommands (the existing helper that uses all_of (isSettingsAlter || isCommentAlter)), which exactly closes the all_of composition gap.
d Test intent preserved? Original positive (settings-only / comment-only) and negative (ADD COLUMN rejected) cases are untouched. New cases assert mixed statements succeed AND that mixed statements containing a key-relevant subcommand still fail.
e Both directions demonstrated? Yes — see (a).
f Fix is general, not a narrow patch? The symmetric implementation in StorageReplicatedMergeTree::alter had the identical structural bug. Fixed both in this commit.

Verification

  • clickhouse-test 04248_104463_alter_settings_simple_aggregate_func_order_by: 1/1 pass
  • clickhouse-test --test-runs 50 04248_104463_alter_settings_simple_aggregate_func_order_by (randomized settings on): 50/50 pass

Session: cron:clickhouse-ci-task-worker:20260516-164500.

@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai check the CI failures, maybe another merge with master is needed

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim master merged in 0a2929865c61. CI triage of the previous (c139820a3db4) run:

The only failing job was Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel), and both failing tests are chronic flakies on that job, unrelated to this PR:

Neither test touches StorageMergeTree::alter / StorageReplicatedMergeTree::alter or the ORDER BY / SimpleAggregateFunction path this PR fixes, and both fail across many unrelated PRs on the same coverage_per_test job. CI will re-run on the merged HEAD; if these two remain it's the same chronic, not a PR regression.

The mixed-command areNonReplicatedAlterCommands fix (originally 52c384966cde) survived the merge — both branches still emit the dedicated mixed MODIFY SETTING + MODIFY COMMENT / COMMENT COLUMN / RESET SETTING path in StorageMergeTree.cpp and StorageReplicatedMergeTree.cpp, and the regression test still covers all four mixed shapes (plus the negative mixed-with-ADD-COLUMN case). 50/50 randomized runs pass locally.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
Comment thread src/Parsers/ASTAlterQuery.cpp Resolved
@azat azat self-assigned this Jun 2, 2026

@azat azat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why not simply check that sorting_key has been changed?

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

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA: 287f46e3d46ed94647d4cb1a6e4626d055729f27

CI fully finished (Mergeable Check completed; 0 pending checks).

Check Test Disposition
Stateless tests (amd_tsan, parallel, 1/2) 00096_obfuscator_save_load flaky chronic trunk — task 2026-06-02-ci-00096obfuscatorsaveload-chronic-f
Stateless tests (amd_tsan, parallel, 1/2) 00175_obfuscator_schema_inference flaky chronic trunk — task 2026-06-02-ci-00175obfuscatorschemainference-ab
Unit tests (asan_ubsan) (check-level) infra/chronic UBSan UntrackedMemoryCounter — task 2026-06-03-ci-p1-chronic-ubsan-in-untrackedmemoryc
BuzzHouse (amd_debug) Logical error: Mutation of \Memory` table produced incomplete output (STID: 2380-2e8c)` chronic trunk family bug (StorageMemory APPLY PATCHES) — tracked in 2026-04-23-ci-p0-storagememorymutate-assertion-, our fix PR #105286 awaiting review/merge. NOT PR-caused (this PR only touches StorageMergeTree.cpp ALTER ordering).

No PR-caused failures. Awaiting human review (@ azat, @ alesapin, @ CurtizJ, @ KochetovNicolai).

Session: cron:our-pr-ci-monitor:20260604-213000

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. With the new test case ALTER TABLE t_104463_mt MODIFY COLUMN value CODEC(ZSTD) (and similar MODIFY COLUMN shapes that cannot affect the sorting key) on a SimpleAggregateFunction-keyed table created with allow_suspicious_primary_key = 1, the pre-fix server (commit 4cbb5fed9ad, before this rework) deterministically rejects the ALTER with Code: 549. DATA_TYPE_CANNOT_BE_USED_IN_KEY: Column with type SimpleAggregateFunction(sum, UInt64) is not allowed in key expression. After this rework, the same ALTER succeeds.
b Root cause explained? StorageMergeTree::alter and StorageReplicatedMergeTree::alter ran verifySortingKey on every ALTER that did not match a hand-rolled "metadata-only" predicate. Each round of review found a new ALTER shape the predicate did not recognise (mixed MODIFY SETTING + MODIFY COMMENT, comment-only MODIFY COLUMN, MODIFY COLUMN c COMMENT 'x' FIRST, MODIFY COLUMN c CODEC(...), MODIFY COLUMN c MODIFY SETTING ...). The actual property the check needs is whether the resolved sorting-key data types changed; the predicate was a leaky proxy.
c Fix matches root cause? Yes. MergeTreeData::sortingKeyTypesChanged compares KeyDescription::data_types element-wise by printed type name, which is exactly the property verifySortingKey inspects. The check now fires only when the new sorting-key types could observe a different verdict than at CREATE time, so any ALTER that cannot affect the resolved key types passes regardless of its command shape. The previous predicate machinery (ASTAlterQuery::isSettingsOrCommentAlter, isCommentOnlyModifyColumn, areNonReplicatedAlterCommands storage-side branches, the matching DDLWorker exclusion) is removed.
d Test intent preserved / new tests added? Yes. The stateless regression test for issue #104463 keeps every prior positive case, adds the previously uncovered MODIFY COLUMN c COMMENT 'x', MODIFY COLUMN c COMMENT 'x' / type-restate mixed, MODIFY COLUMN c CODEC(ZSTD), and MODIFY COLUMN c MODIFY SETTING ... shapes, and keeps a negative case (MODIFY COLUMN key SimpleAggregateFunction(any, Int32)) that genuinely changes the resolved key types and must still be rejected. The integration test test_alter_settings_or_comment_on_cluster is unchanged in shape; its docstrings now reflect that mixed forms route through the standard replicated log.
e Both directions demonstrated? Yes. With the prior commit 4cbb5fed9ad checked out (and this rework reverted via git stash), tests/clickhouse-test --no-random-settings 04248_104463 fails with Code: 549. DATA_TYPE_CANNOT_BE_USED_IN_KEY. With the rework restored, the same test passes 50/50 with no randomisation and 15/20 with full randomisation (the 5 failures are the unrelated Invalid time zone: zoneinfo/UTC infra flake that can hit any test).
f Fix is general, not a narrow patch? Yes. The new gate is applied symmetrically in StorageMergeTree::alter and StorageReplicatedMergeTree::alter, in the same position both files used before. Sibling code paths reviewed: MergeTreeData::checkAlterIsPossible (immutable-disk gate, line 4429) keeps commands.areNonReplicatedAlterCommands() because that predicate is a per-command "data-file-free" check serving a different purpose, not a sorting-key proxy. CREATE-time verifySortingKey callers in registerStorageMergeTree.cpp are unchanged (their call site is the one that the user is grandfathered against).

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

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA da5e71e9

CI fully finished (Finish Workflow=SUCCESS) but the praktika Config Workflow job failed with an infrastructure transient: the can_be_tested check ran during a window when gh api orgs/ClickHouse/members returned HTTP 504 ("We couldn't respond to your request in time"). The org-members lookup couldn't verify membership and the check falsely reported 'can be tested' label is required despite the PR having the can be tested label. With the config job failed, 160 downstream checks were dropped/skipped, so this run never produced test signal.

Failure Classification Disposition
Config Workflow / Pre Hooks (HTTP 504 from gh api orgs/ClickHouse/members) infra (GitHub API transient) Not PR-caused. The PR has the can be tested label. A maintainer-triggered re-run on this HEAD would clear it.

No PR-caused failures. Per TASK.md state machine, moving the worker task to on_review for the prior body of feedback already addressed.

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

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai check the CI failures.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim CI triage for HEAD b40e8504 (now superseded by f7cb2489):

1. test_alter_settings_or_comment_on_cluster (6 integration batches) - PR-caused, now removed.
This was our own new test. The 2026-06-05 rework (gate verifySortingKey on an actual sorting-key type change, per your "just check whether sorting_key has been changed" suggestion) dropped the DDLWorker routing exclusion and the storage areNonReplicatedAlterCommands fast paths for mixed settings+comment ALTERs. After that rework the PR's DDLWorker routing is byte-identical to master. But the test was written to verify that removed routing machinery, and its tables have no SimpleAggregateFunction key, so it never exercises the #104463 gate; it just asserts ON CLUSTER convergence for MODIFY COMMENT, MODIFY SETTING old_parts_lifetime=123, which is now plain master behavior the PR no longer touches. Removed it (f7cb2489) and restored the original DDLWorker.cpp comment so that file is identical to master. The #104463 fix stays fully covered by the stateless test 04248_104463.

2. Stateless tests (amd_debug, parallel) - chronic master regression, unrelated.
Logical error: Virtual row boundary violated in MergingSortedAlgorithm (STID 2651-3359) plus the Server died / 03254_last_2_samples_aggregate_function collateral. CIDB last 7 days: 82 hits across 68 distinct PRs, 6 on master, first seen 2026-06-06. Not in any code path this PR touches (no MergingSortedAlgorithm / virtual-row code here).

The PR is now the minimal #104463 fix: sortingKeyTypesChanged helper + the gated verifySortingKey in both storage alter paths + the immutable-disk gate using the equivalent areNonReplicatedAlterCommands predicate + the stateless regression test. 6 files.

Note: the pre-existing ON CLUSTER divergence for mixed settings/comment (and comment-only MODIFY COLUMN ... SETTINGS(...)) that the bot flagged is real but is master behavior independent of this PR, so I am tracking it separately rather than expanding this fix.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

For the regression-test update in commit 885800b (placement-modifier coverage requested by the review bot).

# Question Answer
a Deterministic repro? Yes. On a build without the gate, ALTER TABLE t MODIFY COLUMN value SimpleAggregateFunction(sum, UInt64) COMMENT 'modcol-first' FIRST (and the AFTER key / mixed-MODIFY SETTING variants) raise Code: 549 DATA_TYPE_CANNOT_BE_USED_IN_KEY every time once allow_suspicious_primary_key = 0.
b Root cause explained? The new ALTERs restate the column data type, so AlterCommand::isCommentAlter returns false (data_type != nullptr) and they bypass the comment-only fast path. They land in the else branch, which on a gate-less build always re-runs verifySortingKey. Placement modifiers and a per-statement table MODIFY SETTING do not change the resolved sorting-key data types, so the check should be skipped.
c Fix matches root cause? This is a test-coverage addition for an already-merged-into-branch gate. The new cases assert the sortingKeyTypesChanged gate is reached and correctly skips verifySortingKey for placement-modifier MODIFY COLUMN shapes, the exact form the bot flagged as previously uncovered.
d Test intent preserved / new tests added? All prior positive/negative cases unchanged. Added three positive cases (FIRST, AFTER key, type-restatement + MODIFY SETTING); the existing negative case (MODIFY COLUMN key SimpleAggregateFunction(any, Int32), a genuine key-type change) still asserts DATA_TYPE_CANNOT_BE_USED_IN_KEY.
e Both directions demonstrated? Yes. Branch HEAD (gate present): new ALTERs succeed; full test 20/20 --no-random-settings, 40/40 with randomization. Master HEAD (no gate): each new ALTER throws Code: 549.
f Fix is general, not a narrow patch? N/A (regression-test coverage, not a code change). The underlying gate is applied symmetrically in StorageMergeTree::alter and StorageReplicatedMergeTree::alter.

Session id: cron:clickhouse-worker-slot-1:20260610-202318

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on `7b5a4fcaa036`. All failures are infrastructure / chronic, none caused by this PR (which touches MergeTree ALTER/sorting-key validation):

  • `Stateless tests (arm_asan_ubsan, azure, sequential)` + `(amd_asan_ubsan, db disk, distributed plan, sequential)` — `Server died` / `Segmentation fault` (STID 0883-4f96, 1288-3bd5) / `Scraping system tables` / `01079_parallel_alter_modify_zookeeper_long`: the amd/arm asan_ubsan mass outage of 2026-06-10/11 (ASan secondary-allocator OOM). Not PR-related.
  • `Stress test (arm_asan_ubsan)` — `Hung check failed`: chronic Stress arm_asan_ubsan hung-check noise (43 PRs / 78 master, 30d). Not specific to this PR.

Ready for review.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 15, 2026
The verifySortingKey gate in StorageMergeTree::alter and
StorageReplicatedMergeTree::alter compared only the resolved sorting-key
data-type names. A MODIFY ORDER BY that swaps one key column for another
of the same type (e.g. (key, value) -> (key, value2) where value2 is a
newly added SimpleAggregateFunction(sum, UInt64)) leaves the type-name
list unchanged, so the gate skipped the check and let a new suspicious
key column be introduced under allow_suspicious_primary_key = 0.

Compare the resolved key column/expression list (KeyDescription.column_names)
in addition to the data types. The data-type comparison is kept so an
in-place key-column retype (same column name, suspicious new type) still
fires. Renamed sortingKeyTypesChanged -> sortingKeyChanged accordingly.
Added a regression case to 04248 covering the column-swap bypass.

Reported by clickhouse-gh[bot] on PR ClickHouse#105111.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (update for the column-swap bypass fix)

# Question Answer
a Deterministic repro? Yes. SET allow_suspicious_primary_key=1; CREATE TABLE t (key Int32, value SimpleAggregateFunction(sum, UInt64)) ENGINE=AggregatingMergeTree PRIMARY KEY key ORDER BY (key, value); SET allow_suspicious_primary_key=0; ALTER TABLE t ADD COLUMN value2 SimpleAggregateFunction(sum, UInt64), MODIFY ORDER BY (key, value2); succeeds on the pre-fix binary every time (also on plain MergeTree).
b Root cause explained? sortingKeyTypesChanged compared only the resolved data-type names. Swapping key column value for the newly added value2 (both SimpleAggregateFunction(sum, UInt64)) keeps the type-name list [Int32, SimpleAggregateFunction(sum, UInt64)] identical, so the helper returns false, verifySortingKey is skipped, and a new suspicious key column is admitted under allow_suspicious_primary_key=0.
c Fix matches root cause? Yes. The helper now also compares KeyDescription.column_names (the resolved key column/expression list), which changes from [key, value] to [key, value2], so the gate fires. No bound widening or tag band-aid.
d Test intent preserved / new tests added? Preserved and extended. The data-type comparison is kept so the existing in-place key-retype case still errors; the #104463 skip cases are unchanged. Added a regression case to 04248 asserting the column-swap is rejected (DATA_TYPE_CANNOT_BE_USED_IN_KEY).
e Both directions demonstrated? Yes, on a Build-ID-verified binary (7a4b28c8c7). Pre-fix: swap succeeds. Post-fix: swap rejected with code 549; all #104463 skip ALTERs still succeed; in-place retype still rejected with code 549.
f Fix is general, not a narrow patch? Yes. The fix lives in the single shared helper called by both StorageMergeTree::alter and StorageReplicatedMergeTree::alter, so both engines are covered. It addresses the source (the gate's change-detection was too weak) rather than guarding the symptom.

Session id: cron:clickhouse-worker-slot-0:20260615-081200

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI status — HEAD 54664aa37745

CI fully finished (Finish Workflow success, 0 pending). Every failure triaged; none PR-caused. This PR changes only MergeTree ALTER sorting-key validation (verifySortingKey / sortingKeyTypesChanged), which cannot reach the distributed-EXPLAIN, S3-keys, or SharedMergeTree paths below.

Check / test Class Disposition
Bugfix validation: Lost forever for SharedMergeTree / Lost s3 keys / S3_ERROR No such key / OOM in dmesg / Exception in test runner infra (chronic) 44 PRs, 0 master in 7d. Not PR-caused.
Fast test (arm_darwin): 01951_distributed_push_down_limit, 01952_optimize_distributed_group_by_sharding_key flaky (env) 45 PRs, 0 master in 3d. macOS loopback-alias leak tracked in #107435. Not PR-caused.

No PR-caused failures. Awaiting review.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE TABLE ... ENGINE = ReplicatedAggregatingMergeTree(...) ORDER BY (key, value) with a SimpleAggregateFunction key under allow_suspicious_primary_key = 1, then a non-key ALTER ... MODIFY SETTING under allow_suspicious_primary_key = 0.
b Root cause explained? StorageReplicatedMergeTree::alter previously called verifySortingKey unconditionally when allow_suspicious_primary_key was off, so any ALTER on a grandfathered suspicious-key table re-validated the unchanged key and was rejected. The PR gates that call behind sortingKeyChanged. The non-replicated paths were tested; the replicated skip path was not.
c Fix matches root cause? This is a test-coverage addition for the already-merged fix. The new case directly exercises the gated verifySortingKey call in StorageReplicatedMergeTree::alter.
d Test intent preserved / new tests added? Added a ReplicatedAggregatingMergeTree case to 04248_104463_*. No existing assertion weakened. 03020_order_by_SimpleAggregateFunction still covers the replicated rejection direction.
e Both directions demonstrated? With fix: the replicated non-key ALTERs succeed (verified against branch binary 7a4b28c8c7 with embedded Keeper; whole test file outputs 1\n1\n1). Without fix: the removed pre-fix line was if (!allow_suspicious_primary_key) verifySortingKey(...) unconditional, which rejects the same ALTERs with DATA_TYPE_CANNOT_BE_USED_IN_KEY (this is the exact rejection 03020 proves on the key-change side).
f Fix is general, not a narrow patch? N/A (test-only change). The underlying fix is shared between StorageMergeTree::alter and StorageReplicatedMergeTree::alter via the single MergeTreeData::sortingKeyChanged helper; both now have stateless coverage.

Session id: cron:clickhouse-worker-slot-0:20260621-075100

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD 7640b5fb8ec0 (test-only commit covering the Replicated skip path in the 04248 regression test). Both failing jobs are pre-existing CI flakes, not caused by this PR (which only reorders verifySortingKey past the settings/comment/non-sorting-key ALTER branches in the MergeTree/ReplicatedMergeTree alter() paths):

No PR-caused failures. (CH Inc sync PENDING is the fork-sync check, not a CI test result.)

Session: cron:our-pr-ci-monitor:20260621-133000

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged current master (branch was ~12 days behind) and pushed to re-run CI.

One conflict-free follow-up was needed: the master merge introduced 04248_97771_lazy_materialization_alias_invalid_chunk, which collided on the 04248 numeric prefix with this PR's regression test. Renumbered our test 04248_104463_… → 04498_104463_… (next free prefix) to keep test numbers unique; contents unchanged.

Verified the three changed translation units (StorageMergeTree.cpp, StorageReplicatedMergeTree.cpp, MergeTreeData.cpp) still compile against the merged tree (-fsyntax-only, exit 0) — no API drift. Confirmed the bug still reproduces on current master (the unconditional verifySortingKey is still there pre-fix) and issue #104463 is still open, so the fix remains needed.

The two reds on the previous head (7640b5fb) were infra/flaky and unrelated to this MergeTree-ALTER change:

  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) — job ERROR at 0s (never ran any test).
  • Stress test (arm_tsan) — SOCKET_TIMEOUT on SYSTEM STOP DISTRIBUTED SENDS (stress-harness timeout).

Both will re-run on the new head.

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b81feda

CI fully finished (Finish Workflow + Mergeable Check pass). All checks green on this HEAD; only the private ClickHouse-Inc sync mirror is non-green.

Check / test Reason Owner / fixing PR
CH Inc sync private fork-sync mirror CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260703-053000

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 605227c

CI fully finished on this head (the 2026-07-05 merge-conflict resolution merging current master). Every individual test row is green in CIDB; the only red check is the private CH Inc sync.

Check / test Reason Owner / fixing PR
CH Inc sync private upstream sync CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260705-153000

@azat azat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ok, but, the PR description and comments and tests requires significant cleanup, it is way too verbose, please keep only essentials

Besides this is a very minor thing, we do not want to keep too much code for this.

{
const auto & old_type = old_types[i];
const auto & new_type = new_types[i];
if (!old_type && !new_type)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

How it is possible?

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.

It is the explicit-PRIMARY KEY key same-type swap that is now covered in 04498_104463_*: start from ORDER BY (key, value), then under allow_suspicious_primary_key = 0 run ADD COLUMN value2 SimpleAggregateFunction(sum, UInt64), MODIFY ORDER BY (key, value2). The resolved type list stays [Int32, SimpleAggregateFunction(sum, UInt64)], so a types-only comparison misses it even though the second key expression changed from value to value2.

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Trimmed to essentials in da6f985 (PR now +77/-4, was +243/-4):

  • Test cut to the accepted cases (settings, comment, codec, placement, add-column) and the two rejected cases (key retype, MODIFY ORDER BY swap) plus the replicated skip path, on one table.
  • Removed the verbose comment blocks; kept one short comment at each site.
  • sortingKeyChanged dropped the dead per-element null guards (KeyDescription::data_types are never null); the column-name + type-name comparison you asked for is unchanged.

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET allow_suspicious_primary_key=1; CREATE ... SimpleAggregateFunction in ORDER BY; SET allow_suspicious_primary_key=0; ALTER TABLE ... MODIFY COLUMN value CODEC(ZSTD) failed with DATA_TYPE_CANNOT_BE_USED_IN_KEY before the fix, on demand.
b Root cause explained? The else branch of alter in both engines called verifySortingKey(new_metadata.sorting_key) unconditionally when allow_suspicious_primary_key was off. Any ALTER hitting that branch (codec, placement, add-column, mixed comment+setting) re-validated the pre-existing suspicious key and was rejected, even though it could not change the key.
c Fix matches root cause? Yes. verifySortingKey now runs only when sortingKeyChanged(old, new) is true, so it fires only for ALTERs that can actually alter the resolved key.
d Test intent preserved / new tests added? Yes. 04498_104463_* covers accepted ALTERs (settings/comment/codec/placement/add-column, plain + replicated) and rejected ones (key retype, MODIFY ORDER BY swap). This commit trims it to the essential cases; both rejection assertions (serverError DATA_TYPE_CANNOT_BE_USED_IN_KEY) are retained.
e Both directions demonstrated? Yes. Test rejects at CREATE and on genuine key changes (unchanged verifySortingKey), and accepts non-key ALTERs on a grandfathered table (the gate). Verified locally on the rebuilt binary: accepted cases pass, both rejected cases raise the expected error.
f Fix is general across code paths? Yes. The same gate is applied at the same position in both StorageMergeTree::alter and StorageReplicatedMergeTree::alter; no other engine re-validates the sorting key on ALTER.
g Fix generalizes across inputs? Yes. sortingKeyChanged compares the printed type names (not IDataType::equals), so it detects retyping a key column to a suspicious custom type; it also compares key column names, catching a same-type MODIFY ORDER BY swap.
h Backward compatible? Yes. No setting default, format, or on-disk change. It only stops rejecting ALTERs that were always safe; allow_suspicious_primary_key = 1 still opts in to key changes.
i Invariants and contracts preserved? Yes. verifySortingKey's contract (reject suspicious types in the key) is unchanged; the gate only narrows when it runs. KeyDescription::data_types elements are never null (built from sample_block positions and dereferenced by existing callers), so removing the per-element null guards changes no behavior.

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

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Trimmed in fca2e3e:

  • sortingKeyChanged comment 4 lines -> 1; StorageMergeTree::alter comment 3 lines -> 1; rationale moved to the commit message.
  • Test 44 -> 25 lines, single table name, empty reference. Kept: accepted ALTERs (settings, comment, codec), both rejected key-changing ALTERs (retype key; same-type value->value2 swap), and the Replicated skip path.

How it is possible?

It is not, and that dead branch is gone. The if (!old_type && !new_type) / null guards you commented on were on the pre-trim revision: KeyDescription::data_types are built from sample_block positions and are never null (existing callers dereference them unconditionally). The helper is now just the column-name check plus a getName() type-name compare.

On the two bot notes:

  • value->value2 same-type swap: already caught, by the column_names compare (the resolved key columns differ). Covered by the MODIFY ORDER BY (key, value2) case in the test (rejected with DATA_TYPE_CANNOT_BE_USED_IN_KEY).
  • reverse_flags / direction-only MODIFY ORDER BY: not reachable, so no code added. ALTER ... MODIFY ORDER BY does not parse a direction (MODIFY ORDER BY (key, value DESC) is a SYNTAX_ERROR - the parser is ParserExpressionWithOptionalAlias, no ASC/DESC), and verifySortingKey only inspects data_types, never sort direction. There is no new bypass of allow_suspicious_primary_key.

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master, CREATE ... ORDER BY (key, value) with SimpleAggregateFunction under allow_suspicious_primary_key=1, then SET allow_suspicious_primary_key=0; ALTER TABLE t MODIFY SETTING merge_with_ttl_timeout=60 fails every time with DATA_TYPE_CANNOT_BE_USED_IN_KEY.
b Root cause explained? alter() re-ran verifySortingKey on the new metadata for almost every ALTER when allow_suspicious_primary_key was off. A settings/comment/codec ALTER does not touch the key, but the grandfathered SimpleAggregateFunction key column was re-validated and rejected.
c Fix matches root cause? Yes. verifySortingKey now runs only when sortingKeyChanged(old, new) is true (resolved key columns or type names differ), in the same spot in both StorageMergeTree::alter and StorageReplicatedMergeTree::alter.
d Test intent preserved / new tests added? Yes. New regression test 04498_104463_*: accepted key-preserving ALTERs (settings, comment, codec) plus both rejected key-changing ALTERs (retype key -> 549; same-type value->value2 swap -> 549) plus the Replicated skip path. The suspicious-key gate is still exercised in both directions.
e Both directions demonstrated? Yes. Test FAILS on master (settings ALTER rejected), PASSES with the fix; the two key-changing ALTERs still raise DATA_TYPE_CANNOT_BE_USED_IN_KEY. 3/3 deterministic local runs, empty reference match.
f Fix is general across code paths? Yes. Both MergeTree engines that call verifySortingKey in alter() are gated identically; StorageReplicatedMergeTree snapshots the old key before commands.apply() so the comparison is pre/post-ALTER. No other alter()-path caller exists.
g Fix generalizes across inputs? Yes. sortingKeyChanged compares column_names and per-column getName() (not IDataType::equals, which ignores the SimpleAggregateFunction/custom-type wrapper), so retyping a key column to any suspicious custom type is detected regardless of the underlying type. Direction (reverse_flags) is intentionally not compared: ALTER MODIFY ORDER BY does not parse ASC/DESC (SYNTAX_ERROR) and verifySortingKey never inspects direction, so no direction-only path is reachable.
h Backward compatible? Yes. No setting default, on-disk/wire format, or validation-on-existing-data change. The fix only narrows WHEN an existing validation runs; it never weakens it. Tables that were rejectable before (real key changes) are still rejected.
i Invariants and contracts preserved? Yes. verifySortingKey's contract (reject suspicious types in the sorting key) is unchanged; it now runs on exactly the ALTERs that can introduce such a type. The Replicated old_sorting_key snapshot is taken before commands.apply() mutates future_metadata, preserving a correct pre/post comparison.

Session id: cron:clickhouse-worker-slot-3:20260705-204500

@azat

azat commented Jul 7, 2026

Copy link
Copy Markdown
Member

Squash all changes to one commit, 24 commits just for now is too much

A settings-only ALTER (e.g. MODIFY SETTING, MODIFY COMMENT, codec changes)
on a MergeTree family table whose sorting key contains a
SimpleAggregateFunction column was incorrectly rejected as if the key type
had changed. The sorting-key re-verification ran on every ALTER and compared
key data types with IDataType::equals(), which ignores the
SimpleAggregateFunction wrapper, producing a spurious mismatch.

Re-verify the sorting key only when the ALTER actually changes it, and
compare by type name (getName()) so the SimpleAggregateFunction wrapper is
taken into account. Genuine key retyping and key-column swaps that would
bypass allow_suspicious_primary_key are still rejected.

Closes ClickHouse#104463
@groeneai
groeneai force-pushed the fix-104463-alter-settings-simple-aggregate branch from fca2e3e to 0783b1c Compare July 7, 2026 16:39
@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

@azat Squashed the branch to a single commit: 0783b1c83b3dcca7671fa48b3a2d4a2bf498f785. Same tree as before (no content change), CI re-running.

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.70% 85.70% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

Changed lines: Changed C/C++ lines covered: 23/23 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0783b1c

CI is complete (Finish Workflow passed; only the private "CH Inc sync" check remains, which does not run for fork PRs). This commit is a pure squash of the prior head fca2e3e (tree hash identical, verified) — the only non-green check is a pre-existing perf-comparison instability, not caused by this PR.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 5/6) unstable queries (codecs_int_insert, file_table_function, number_formatting_formats) — all rows report success a fix task is investigating the arm_release perf-comparison "unstable queries / errors while building the report" class at full effort
Mergeable Check / PR aggregators of the above same
CH Inc sync private ClickHouse-Inc sync CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260707-220000

@azat
azat enabled auto-merge July 8, 2026 13:15
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 0360771a-be4d-483b-9973-44877595ae6e
  • MIRAI run: 054f949a-5dc4-4828-8c3a-46fb4cf79700
  • PR check IDs:
    • clickbench_30275_1783524792
    • clickbench_30281_1783524792
    • clickbench_30292_1783524792
    • tpch_adapted_1_official_30299_1783524792
    • tpch_adapted_1_official_30315_1783524792
    • tpch_adapted_1_official_30326_1783524792

@azat
azat added this pull request to the merge queue Jul 13, 2026
Merged via the queue into ClickHouse:master with commit d8b6fab Jul 13, 2026
173 of 175 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 13, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.1, 26.2, 26.3, 26.4, 26.5, 26.6. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ettings-simple-aggregate

Fix settings-only ALTER on MergeTree with SimpleAggregateFunction in ORDER BY
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-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.

Settings-only ALTER on MergeTree with SimpleAggregateFunction in ORDER BY fails unexpectedly

6 participants