Skip to content

Refuse a MODIFY COLUMN default that would leave old parts unsorted by the sorting key - #124234

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-modify-column-default-of-sorting-key-column
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-modify-column-default-of-sorting-key-column

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #71777
Related: #121943

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

ALTER TABLE ... MODIFY COLUMN now rejects giving a sorting key column that is not in the primary key a DEFAULT or MATERIALIZED expression that is not deterministic or reads more than the sorting key columns before it (a constant is fine), unless its previous expression already did. Parts written before such a column was added to the sorting key with MODIFY ORDER BY do not store it and compute it from that expression, so SELECT ... ORDER BY returned unsorted rows and merges of those parts failed with Sort order of blocks violated.

Description

On 26.3.42.3 and 26.8.18.2, ALTER TABLE t MODIFY COLUMN k DEFAULT x + y on a column added to the sorting key by MODIFY ORDER BY makes SELECT ... ORDER BY a, k return unsorted rows:

CREATE TABLE t (a UInt32, x UInt32, y UInt32) ENGINE = MergeTree ORDER BY a;
INSERT INTO t VALUES (1, 30, 10), (1, 10, 1);
ALTER TABLE t ADD COLUMN k UInt32, MODIFY ORDER BY (a, k);
ALTER TABLE t MODIFY COLUMN k UInt32 DEFAULT x + y;
SELECT a, k FROM t ORDER BY a, k; -- (1,40), (1,11)

MODIFY ORDER BY is accepted only because old parts read the new column as a constant, and checkProperties forbids a default for it in the same ALTER, but a later MODIFY COLUMN was not checked. checkAlterEligibility now refuses changing what such a column computes from a deterministic expression of the bare sorting key columns before it that are not Float, Nullable or dynamic to anything else. Only primary and partition key columns are exempt: every part stores them.

Metadata cannot tell such a column from one in the sorting key since CREATE with a shorter PRIMARY KEY, so a column whose expression already breaks the rule (k DEFAULT x) can still change if the key reads it as is, while one that follows it cannot get a breaking one. Checking the parts is not sound: one can arrive via ATTACH PARTITION FROM, a detached part or a replica.

03263_forbid_materialize_sort_key built this state, and its merges are the Float64 Sort order of blocks violated stress failures, e.g. Stress test (amd_debug).


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

groeneai and others added 2 commits October 6, 2026 12:54
… of old parts

`ALTER ... ADD COLUMN k, MODIFY ORDER BY (a, k)` is accepted because parts
written before it do not store `k` and read it as the type default, a
constant, so they stay sorted by `(a, k)`. `checkProperties` enforces this for
the same ALTER (a newly added key column may not have a default), but a later
`ALTER MODIFY COLUMN k DEFAULT|MATERIALIZED <expr>` was not checked: readers of
the old parts then compute `k` per row from `<expr>`, which the parts were never
sorted by. `SELECT ... ORDER BY a, k` returns unsorted rows (with and without
`optimize_read_in_order`), and every merge of such a part aborts in
`CheckSortedTransform` on debug and sanitizer builds (release builds write a
part that is not sorted by its own key). Test 03263 builds exactly this state
with `MODIFY COLUMN b DEFAULT rand64() % 100000`, which is where the Float64
`Sort order of blocks violated` stress aborts come from.

`checkAlterEligibility` (initial query only) now refuses a MODIFY COLUMN that
changes what a sorting key column, other than the columns every part stores
since CREATE (primary key and partition key columns, and the engine's sign,
version and is_deleted columns), computes from its DEFAULT or MATERIALIZED
expression, unless that expression is deterministic and reads only bare primary
key columns. Such an expression is constant over each run of equal primary key
values, which is what keeps the old parts sorted. The engine's columns are named
in the engine arguments, must exist at CREATE, cannot be dropped or renamed, and
`MODIFY ORDER BY` adds only columns added by the same ALTER, so one of them in
the sorting key is in every part. Float, Dynamic, Variant, Object
(`comparisonCanMergeDistinctValues`, now shared from SortDescription) and
Nullable primary key columns are excluded, because rows that compare equal on
them can still differ. The check looks at the final metadata of the ALTER, and
also fires when a column in the expression's dependency closure changes (an
ALIAS, an EPHEMERAL or a DEFAULT the reader evaluates on the way), as
`evaluateMissingDefaults` follows that closure. ALTERs that do not touch the
closure are not refused, so a table an older version left in the bad state stays
alterable, and `MODIFY COLUMN k REMOVE DEFAULT` stays allowed.

Constant defaults (ClickHouse#13592's workaround) and primary-key-determined defaults
(04626) stay accepted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove a comment that narrated the ALIAS-dependency filter; it follows from the ExpressionSources::columns doc.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Oct 6, 2026
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 rounds, 3 findings) plus my own cold review.

# Sev Finding Verdict Evidence / action
1 ❌ A ReplacingMergeTree version (or is_deleted, or Collapsing sign) column listed in ORDER BY with a shorter PRIMARY KEY was refused, although it exists since CREATE and every part stores it AGREE, fixed engine sign/version/is_deleted columns are exempt like the primary and partition key columns
2 ⚠️ The sign-column exemption was not exercised by the test AGREE, fixed CollapsingMergeTree arm whose sign default reads a modified column
3 ❌ k DEFAULT p.q with p ALIAS tuple(a) is accepted, but reads of old parts fail with UNKNOWN_IDENTIFIER DISAGREE the failure is in the missing-default read path (injectRequiredColumnsRecursively cannot resolve a subcolumn of an ALIAS), which this PR does not touch and which fails the same way on master and for non-key columns; it never yields unsorted rows
4 ⚠️ A non-primary-key sorting key column present since CREATE is refused too, as metadata cannot tell it from a later-added one AGREE stated in the PR description, with the narrower alternative
5 💡 "REMOVE DEFAULT repairs it" overclaimed: parts already merged in the bad state keep the unsorted values AGREE, fixed description and commit message reworded

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The 5-statement SQL in the description returns (1,40), (1,11) on master, 26.3.42.3 and 26.8.18.2 every time; OPTIMIZE FINAL then aborts in CheckSortedTransform on a debug build.
b Root cause explained? Parts written before MODIFY ORDER BY added k do not store it; after MODIFY COLUMN k DEFAULT x + y readers compute k per row from that expression, which those parts were never sorted by. Only the same-ALTER case was checked (checkProperties).
c Fix matches root cause? Yes. The ALTER that creates the unsorted state is refused in checkAlterEligibility, next to the ADD COLUMN rule and the MATERIALIZE COLUMN refusal. Reads cannot be fixed without re-sorting parts.
d Test intent preserved / new tests added? New 05331 (12 refused and 16 allowed arms, sorted reads, a debug merge of two parts). 03263 line 6 now expects the error (it built this state, which is where the Float64 stress aborts come from); 04626 is unchanged and passes.
e Both directions demonstrated? 05331 and 03263 FAIL on the master build with "the server error '524' was expected" for each refused line and pass with the fix; 17 mutation arms of the check each turn 05331 (or an upgrade probe) red.
f Fix is general across code paths? The column's own expression and its whole dependency closure (ALIAS chains, EPHEMERAL, DEFAULT columns the reader follows) are checked, on the final metadata of the ALTER; subcolumn keys included; skipped on Replicated database replay like the neighbouring checks.
g Fix generalizes across inputs (params/datatypes/wrappers)? DEFAULT and MATERIALIZED, Wide and Compact; Float, Nullable (incl. LowCardinality(Nullable)) and dynamic primary key types excluded; expression primary keys, a column named like a key expression, Tuple subcolumns, partition key columns and the engine's version, is_deleted and sign columns (VersionedCollapsingMergeTree, ReplacingMergeTree, CollapsingMergeTree) covered by test arms.
h Backward compatible? (maintainer-approved exception only) Existing tables load and read as before, and unrelated ALTERs on them stay accepted. Narrowing: a non-PK sorting key column that existed at CREATE can no longer get a default that reads non-key columns, since metadata cannot tell it from a later-added one. No settings or format change.
i Invariants and contracts preserved? Invariant: every part is sorted by the current sorting key as its readers compute it. The check is metadata-only and throws before any state change. 527 related stateless tests (incl. ZooKeeper ones), 50 randomized runs and a Replicated database run show no regression.

Session id: cron:clickhouse-impl-self-slot-57:20261006-124300

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Oct 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [91eb395]

Summary: ✅


AI Review

Summary

The PR validates changes to sorting-key column defaults so readers of old parts preserve their order. At 91eb39507087, an accepted default change can still turn an ordered part into an unsorted one, and safe migrations on existing tables remain rejected. Both behaviors were reproduced with the exact-head fast-test binary.

Findings

❌ Blockers

  • src/Storages/MergeTree/MergeTreeData.cpp:5922: Failure to prove the old default safe does not prove it already broke the order. A destination with k DEFAULT x - x can attach a part predating k, correctly read (1,0), (1,0), then accept MODIFY COLUMN k DEFAULT x. The same SELECT ... ORDER BY a, k returns (1,30), (1,10). The old-default exemption therefore permits the failure this fix targets. Remove the exemption or replace it with evidence establishing that the column is stored. This is the unresolved case acknowledged in the author's design question; inline finding posted.

  • src/Storages/MergeTree/MergeTreeData.cpp:5918: Existing safe schema migrations still lose compatibility. The earlier thread's k DEFAULT x example is fixed, but the restriction deliberately remains for columns whose old default passes the rule, including no explicit default. For example, this table stores k in every part, yet the final statement now throws ALTER_OF_COLUMN_IS_FORBIDDEN:

    CREATE TABLE t (a UInt32, k UInt64, x UInt32)
    ENGINE = MergeTree ORDER BY (a, k) PRIMARY KEY a;
    INSERT INTO t VALUES (1, 10, 30), (1, 20, 10);
    ALTER TABLE t MODIFY COLUMN k UInt64 DEFAULT x;

    [dismissed by author -- https://github.com/Refuse a MODIFY COLUMN default that would leave old parts unsorted by the sorting key #124234#discussion_r4342528511] The retained restriction still breaks valid migrations without a compatibility setting or migration path. Provide such a path or distinguish historical stored columns. No duplicate inline comment or thread reply was posted.

Tests
  • ⚠️ Add a stateless regression covering an ordered attached part under an old default that fails the sufficient-condition check, such as x - x, followed by an unsafe default change.
  • ⚠️ Cover an allowed default change on a sorting-key column present since CREATE TABLE with no explicit default and a shorter PRIMARY KEY, through the compatibility mechanism chosen for existing tables.
Final Verdict

Status: ❌ Block. Make the old-default exemption sound, preserve a compatibility path for safe existing migrations, and add the two focused regressions.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 6, 2026
@groeneai
groeneai requested review from Avogar and CurtizJ October 6, 2026 14:29
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Object file sizes

5 object files changed (+46.12 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.37 MiB 4.41 MiB +45.80 KiB (+1.02%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

…fore it

A column that is in the sorting key but not in the primary key may now get a
DEFAULT or MATERIALIZED expression that reads the bare sorting key columns
listed before it, not only the primary key columns. Rows with equal values of
those columns are adjacent in every part, so such an expression is constant
over them and the parts that compute the column stay sorted. With
`ORDER BY (a, b, k)` where `b` and `k` were added later,
`MODIFY COLUMN b DEFAULT a` and then `MODIFY COLUMN k DEFAULT b` is now
accepted.

The position matters: a column after it, or one outside the sorting key, is
still refused even when its own default reads only primary key columns,
because parts that do not store `k` can store that column with any values
(`k DEFAULT x` with `x DEFAULT a` returns `(1,30), (1,10)` on master for a
part written before `x` got its default). Expanding the expression through
the defaults of the columns it reads would therefore accept unsorted parts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
for (const auto & key_column : new_metadata.getColumnsRequiredForSortingKey())
{
const String column_name = name_in_storage(key_column);
if (stored_in_every_part.contains(column_name) || !checked.insert(column_name).second)

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.

[P1] Preserve safe default changes on existing sorting-key columns

This also rejects valid changes when k has been stored in every part since CREATE TABLE. For example:

CREATE TABLE t (a UInt32, k UInt32 DEFAULT x, x UInt32)
ENGINE = MergeTree ORDER BY (a, k) PRIMARY KEY a;
INSERT INTO t (a, k, x) VALUES (1, 10, 30), (1, 20, 10);
ALTER TABLE t MODIFY COLUMN k UInt32 DEFAULT x + 1;

The baseline accepts this: existing rows keep their stored k, and subsequent inserts are sorted with their newly computed values. Here, k is excluded from stored_in_every_part, its allowed inputs contain only a, and the last statement throws ALTER_OF_COLUMN_IS_FORBIDDEN. This breaks existing schema migrations without any compatibility setting or other way to retain the safe behavior. The PR description acknowledges the broader rejection, but there is no migration path for these tables. Please distinguish columns that can actually be absent, grandfather existing definitions, or provide a compatibility escape, with a focused regression test for this case.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

In 5f3ba91, a column whose previous expression already breaks the rule, like this k DEFAULT x, can change again (test arm t_s).

…p the order

The check refused every change that leaves a non-primary-key sorting key column with an
expression that does not keep old parts sorted. It cannot tell a column that MODIFY ORDER BY
added from one that is in the sorting key since CREATE, so it also refused changes like
`MODIFY COLUMN k DEFAULT x + 1` for `k DEFAULT x` in `ORDER BY (a, k) PRIMARY KEY a`, and
`MODIFY COLUMN x DEFAULT 5`, which existing schemas may need.

Refuse a change only when the expression kept the order before it. A column added by
MODIFY ORDER BY starts without a default and every later change is checked, so its expression
never stops keeping the order; one that already does not is from CREATE, where every part
stores the column, or from an older version, whose parts without the column are already
computed from such an expression.

Checking the parts instead was considered and rejected: a part without the column can still
arrive after the check (ATTACH PARTITION FROM, a detached part, another replica).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ATTACH PARTITION FROM compares the sorting, primary and partition keys
of the two tables but not their engines, so a part of a plain MergeTree
table that does not store a column can enter a ReplacingMergeTree,
CollapsingMergeTree or VersionedCollapsingMergeTree table in which that
column is the version, is_deleted or sign column. A later
MODIFY COLUMN v DEFAULT x then made that part unsorted, because those
columns were exempt from the check.

Only primary key and partition key columns are stored in every part: no
ALTER adds them, and ATTACH PARTITION FROM requires the same keys.

A column is no longer let through for an old expression that already
breaks the rule unless the sorting key reads it only as the bare
column. The rule judges the whole column, so `t DEFAULT tuple(a, x)`
breaks it while the key element `t.p` stays sorted, and so does
`k DEFAULT x * 2` for `k % 2`; changing them to `tuple(x, x)` and `x`
was accepted and unsorted old parts.

The test now stops merges while it reads computed values, so a
background merge cannot store a column under an intermediate default.

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

Copy link
Copy Markdown
Collaborator Author

@CurtizJ, one design choice here should be yours. The check only proves that an expression keeps the order, so an old expression that fails it may still keep it, like k DEFAULT x - x or k DEFAULT a with a Float64 a. Changing such a default is allowed on the current head, so a part attached without k becomes unsorted:

CREATE TABLE src (a UInt32, x UInt32) ENGINE = MergeTree ORDER BY a;
INSERT INTO src VALUES (1, 30), (1, 10);
ALTER TABLE src ADD COLUMN k UInt32, MODIFY ORDER BY (a, k);
CREATE TABLE dst (a UInt32, x UInt32, k UInt32 DEFAULT x - x) ENGINE = MergeTree ORDER BY (a, k) PRIMARY KEY a;
ALTER TABLE dst ATTACH PARTITION tuple() FROM src;
ALTER TABLE dst MODIFY COLUMN k UInt32 DEFAULT x;
SELECT a, k FROM dst ORDER BY a, k; -- (1,30), (1,10)

Which do you prefer?

  • (A) refuse such changes too: sound and simpler, but a sorting key column outside the primary key whose CREATE default reads other columns can then never change that default (as before 5f3ba91);
  • (B) keep allowing them, as now, so existing schemas keep that migration and these cases stay open.

I lean to (A).

continue;

/// Refusing to change an expression that already breaks the rule, like one from CREATE, protects nothing.
if (!in_key_not_bare.contains(column_name) && !keeps_order(old_metadata, old_identifiers_before, column_name))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Do not treat an unproved old default as already unsorted

keeps_order provides a sufficient condition for preserving order, so its returning false does not establish that the old parts were already unsorted. For example, DEFAULT x - x is constant but fails this predicate. I reproduced the following with the fast-test binary for 91eb39507087:

CREATE TABLE src (a UInt32, x UInt32) ENGINE = MergeTree ORDER BY a;
INSERT INTO src VALUES (1, 30), (1, 10);
ALTER TABLE src ADD COLUMN k UInt64, MODIFY ORDER BY (a, k);
CREATE TABLE dst (a UInt32, x UInt32, k UInt64 DEFAULT x - x)
ENGINE = MergeTree ORDER BY (a, k) PRIMARY KEY a;
SYSTEM STOP MERGES dst;
ALTER TABLE dst ATTACH PARTITION tuple() FROM src;
SELECT a, k FROM dst ORDER BY a, k; -- (1,0), (1,0)
ALTER TABLE dst MODIFY COLUMN k UInt64 DEFAULT x;
SELECT a, k FROM dst ORDER BY a, k; -- (1,30), (1,10)

The ALTER reaches this continue, creating the unsorted-read failure from a previously ordered state. This confirms the unresolved case in the author's design question. Please remove this exemption or base it on evidence that establishes the stored-column invariant, and cover this attachment case with a regression test.

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-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants