Skip to content

Resolve MergeTree key types in the global context on ALTER, not in the ALTER's session - #130154

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/alter-keys-in-global-context
Nov 8, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/alter-keys-in-global-context

Conversation

@groeneai

@groeneai groeneai commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119799
Related: #109196

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed failing merges, an invalid primary index and parts detached as broken after a restart when ALTER TABLE ran with transform_null_in = 1 on a MergeTree table whose sorting or partition key applies IN to a column. ALTER now derives the table's keys in the server's global context, as CREATE and a table reload do.

Description

Found by the targeted AST fuzzer on #130066 (Bad cast from type DB::ColumnNullable to DB::ColumnVector<char8_t>): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130066&sha=f399ce96513dd38be28154da2a435932c87a6cf9&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

On 26.10.2.103, after ALTER TABLE t COMMENT COLUMN x 'c' SETTINGS transform_null_in = 1: with ORDER BY (x IN (1, 2)) every merge fails with NOT_FOUND_COLUMN_IN_BLOCK; with a Nullable sorting key, INSERTs write a primary index of garbage bytes (debug builds abort as above); with PARTITION BY (x IN (NULL, 1)) on a Nullable column, new parts are detached as broken-on-start after a restart. With cast_keep_nullable = 1, the same ALTER is rejected for ORDER BY CAST(x, 'UInt32') over a Nullable column, and with allow_nullable_key = 1 the next INSERT crashes (segmentation fault).

AlterCommands::apply re-derived the keys in the issuing session's context, while CREATE, a reload and the part writers use the global context. transform_null_in rewrites in to nullIn, which renames the key column and, for a Nullable argument, changes its type.

Now the sorting, primary, partition and sampling keys and the minmax_count projection are derived in the global context, as #119799 did for skip indices, keeping the flag that rejects AI functions in keys (#127057). The sampling key moves too because SAMPLE reads its stored type. Projections (#116824) and TTLs are unchanged. A key function needing a session-only setting (detectLanguage) is now rejected by ALTER ... MODIFY ORDER BY as by CREATE; before, such a table rejected every INSERT and could not be attached again. Complements #109196, whose pinned settings lack transform_null_in.

The new test fails on master, each case on its own, and passes with the fix (50/50 randomized runs).


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

Version info

  • Merged into: 26.11.1.1704-master (included in 26.11 and later)

groeneai and others added 2 commits November 8, 2026 12:36
…e ALTER's session

`AlterCommands::apply` re-derived the sorting, primary and partition keys and the
`minmax_count` projection in the context of the session that issued the `ALTER`,
while `CREATE`, a reload of the table and the part writers derive them in the
global context. A session setting that changes key analysis therefore installed
in-memory keys that the table does not really have.

With `transform_null_in = 1`, `in` is rewritten to `nullIn`, which renames the key
column and, for a `Nullable` argument, changes its type from `Nullable(UInt8)` to
`UInt8`. After such an `ALTER` (even a comment-only one):
- an INSERT into a table with a Nullable key under `IN` serialized the writer's
  `ColumnNullable` with the stored `UInt8` serialization: `Bad cast from type
  DB::ColumnNullable to DB::ColumnVector<char8_t>` in debug builds, a primary index
  of garbage bytes in release builds;
- every merge failed with `NOT_FOUND_COLUMN_IN_BLOCK: Not found column in(x, ...)`;
- a partition key wrote `partition.dat` with the session type, so after a restart
  the parts were detached as `broken-on-start`.

Derive these keys in the global context, as ClickHouse#119799 already does for skip indices
in the same function, and carry `isAnalyzingBackgroundExpressions` into it so that
AI functions stay rejected in keys (ClickHouse#127057). The sampling key, projections and
column TTLs keep the session context: the sampling key is re-analysed in the query
context at read time, and projections and TTLs are separate derivations.

Found by the targeted AST fuzzer on PR ClickHouse#130066 (STID 1499-5685).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commit kept the sampling key on the ALTER's session context on the
grounds that it is re-analysed in the query context at read time. That is wrong:
`SAMPLE` takes the sampling universum from the stored `sampling_key.data_types[0]`.
With `cast_keep_nullable = 1` in the `ALTER`'s session, `SAMPLE BY CAST(x, 'UInt32')`
over a `Nullable` column became `Nullable(UInt32)`, and every `SAMPLE` query failed
with `Invalid sampling column type in storage parameters: Nullable(UInt32)` until the
table was reloaded. Derive it with the same key context as the other keys.

The test is renamed to cover both settings, gains a sampling case, and the
ReplicatedMergeTree case now has an explicit `PRIMARY KEY`, so the
`getPrimaryKeyFromAST` branch is covered as well.

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

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, head 9bb2fc8): 2 fixed, 2 dismissed with evidence, 3 noted
Finding Verdict
⚠️ The sampling key was still derived in the ALTER's session, and SAMPLE reads its stored type (cast_keep_nullable = 1 made SAMPLE BY CAST(x, 'UInt32') over a Nullable column Nullable(UInt32)) Fixed in round 1: derived in the global context, plus a SAMPLE case. The reported nullIn name mechanism does not occur: key column names come from the AST
⚠️ The explicit PRIMARY KEY branch was not exercised by the test Fixed in round 1: the ReplicatedMergeTree case declares PRIMARY KEY; reverting only that call aborts it
❌ A comment ALTER on an S3 table whose PARTITION BY needs a session-only setting is now rejected, and a type-affecting setting splits its metadata from the write strategy Dismissed: such a table already fails to load after a restart with the same error, as for skip indices since #119799; nothing reads an object-storage table's partition key types (writes use the partition strategy's own key)
💡 Add an EXPLAIN check for _minmax_count_projection Dismissed: reverting only that call changes no result and no EXPLAIN output (measured)
💡 The SAMPLE case uses only values below the sampling boundary Noted, not blocking: reverting the fix fails it with Nullable(UInt32); the fix cannot change the sampling type's width
💡 The explicit PRIMARY KEY case asserts only count() Noted, not blocking: reverting only that call aborts debug and sanitizer builds (checked assert_cast); case 1 asserts the primary index values
💡 Projections and TTLs stay on the session context Out of scope: projections are tracked in #116824; TTL analysis already uses the server settings

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ORDER BY (x IN (NULL, 1)) on Nullable(UInt64), ALTER ... COMMENT COLUMN x 'c' SETTINGS transform_null_in = 1, then INSERT: server abort on every run on master.
b Root cause explained? AlterCommands::apply derived the sorting, primary, partition and sampling keys in the ALTER's session, while CREATE, a reload and the writers use the global context. transform_null_in rewrites in to nullIn, renaming the key column and changing a Nullable result to UInt8, so the writer serialized a ColumnNullable as UInt8, merges could not find in(...), and parts with such a partition key failed to load after a restart. cast_keep_nullable makes CAST of a Nullable column Nullable, and SAMPLE reads the stored sampling key type.
c Fix matches root cause? Yes. The single divergent derivation site now uses the global context, as #119799 did for skip indices in the same function. No guard at the writer.
d Test intent preserved / new tests added? New test 05571_alter_keys_independent_of_session_settings: Nullable sorting key INSERT, non-Nullable key merge, Nullable partition key reload, sampling key SAMPLE (cast_keep_nullable), ReplicatedMergeTree with an explicit PRIMARY KEY.
e Both directions demonstrated? Yes. The test fails on master (abort) and passes with the fix; each case fails on master on its own; reverting only the partition-key call brings back the partition failure, reverting only the explicit PRIMARY KEY call brings back the ReplicatedMergeTree abort, and without the sampling-key change SAMPLE fails with Nullable(UInt32). 50/50 randomized runs pass.
f Fix is general across code paths? Yes. All key derivations in AlterCommands::apply (sorting, implicit and explicit primary, partition, sampling) plus the minmax_count projection; ReplicatedMergeTree comment/settings-only ALTERs use the same call. Projections and TTLs are separate derivations and unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Nullable(UInt64), LowCardinality(Nullable(String)), LowCardinality(Nullable(BFloat16)) with DESC, non-Nullable UInt64; IN with and without NULL, NOT IN; CAST of a Nullable column under cast_keep_nullable.
h Backward compatible? (maintainer-approved exception only) Yes. Nothing persisted changes and no setting is added. A MODIFY ORDER BY whose key analyses only with a session-only setting is now rejected like CREATE; on master such a table already rejected every INSERT and could not be attached again.
i Invariants and contracts preserved? The in-memory keys now equal what a reload derives. The AI-function rejection flag still reaches key analysis, and the new MODIFY ORDER BY expression is still validated in the session (access checks).

Session id: cron:clickhouse-impl-slot-4:20261108-131300

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @Algunenano, could you review this and add the can be tested label so CI runs? AlterCommands::apply re-derived the sorting, primary, partition and sampling keys in the session of the ALTER, so a setting like transform_null_in gave them types that differ from what CREATE, a reload and the part writers derive in the global context; they now use the global context, as #119799 did for skip indices in the same function.

@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9bb2fc8]

Summary: ✅


AI Review

Summary

Reviewed PR #130154 at 9bb2fc8d05e27fb05aaa9652376151fc426e16a0, including the current diff and all prior discussion. The change resolves sorting, primary, partition and sampling keys, plus the implicit min/max/count projection, using the global context during ALTER, preventing session settings from corrupting key metadata. No actionable findings. The new regression test passed in the Fast test report.

Missing context / blind spots
  • ⚠️ Broader CI is still running. The available workflow-finish report records dropped bugfix-validation jobs following a configuration failure; completed current-head sanitizer and bugfix-validation jobs would close this validation gap. No local build or test run was performed.
Final Verdict

✅ Approve. No code changes requested; normal CI gates still apply. No new inline findings were posted.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov 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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Nov 8, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 8, 2026
Merged via the queue into ClickHouse:master with commit 59e6b4b Nov 8, 2026
373 of 375 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 8, 2026
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Nov 18, 2026
…401`

Master now re-derives the sampling key in the global context after an `ALTER`
(9bb2fc8, ClickHouse#130154), like the
other keys. A session `cast_keep_nullable = 1` therefore no longer makes
`CAST(x AS UInt32)` over a `Nullable` column a `Nullable(UInt32)` sampling key,
and `ALTER TABLE ... MODIFY SAMPLE BY` is accepted instead of failing with
`ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER`. That made `04401` fail in Fast test after
the last master merge.

Update the test case to the new behaviour: the `ALTER` succeeds and `SAMPLE`
keeps working afterwards. Update the comment in `AlterCommand::apply` to match.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109196&sha=35f0e6feeff926f8957a9d1a9cdc72405bc472e6&name_0=PR&name_1=Fast%20test
PR: ClickHouse#109196

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 23, 2026
…ble expressions

Merges and mutations run in a context built from the background profile, so a
function that reads the time zone when it runs (e.g. `toDate` of an `Int64`) is
computed in that profile's `session_timezone`. Under
`SessionTimezoneBlockerInThread` `DateLUT::instance` fell back to the global
context instead, so with a background profile that sets `session_timezone` an
INSERT still wrote parts sorted in another zone than merges recompute
(measured: an INSERT under the same `session_timezone` as the background
profile, which merged on master, aborted with `Sort order of blocks violated`).
Without a background profile its settings are those of the system profile,
which the global context also has, so nothing changes there.

Tests: an integration case with a background profile that sets
`session_timezone` (fails on master and without this change, passes with it);
in 05570 the Graphite block also checks that the rollup happened, and the
`transform_null_in` table, which merges since ClickHouse#130154, now gets two parts, a
merge and a primary key read.

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

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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.

3 participants