Skip to content

Rebuild skip indices, projections, TTL and MATERIALIZED columns left stale by ALTER MODIFY / UPDATE / CLEAR COLUMN - #112717

Open
Avogar wants to merge 32 commits into
ClickHouse:masterfrom
Avogar:fix-stale-subcolumn-skip-index-after-mutation
Open

Avogar wants to merge 32 commits into
ClickHouse:masterfrom
Avogar:fix-stale-subcolumn-skip-index-after-mutation

Conversation

@Avogar

@Avogar Avogar commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

Related: #112302
Related: #85985

A mutation decides what to rebuild by comparing the mutated column against the columns that an index, projection or TTL expression requires. When the expression reads a subcolumn (t.a, json.a) or an ALIAS column, those required columns carry a name the mutation does not track (it tracks the stored column t), so the comparison never matched. On wide parts the dependent files (skp_idx_*, projection parts, TTL infos) were then hardlinked into the mutated part, describing data that no longer exists. Compact parts are unaffected, because a mutation rewrites the whole part. Separately, ALTER MODIFY COLUMN never recalculated MATERIALIZED columns computed from the converted column.

The required columns of such an expression are now resolved by the query analyzer over the table's columns (expressionSourceColumnsInStorage), which follows ALIAS columns and type-dependent functions folded to constants (toTypeName(x)) and reports the columns they are stored in. Where a value is recomputed, subcolumns are read with getSubcolumn from the whole column, so the value comes from the updated column rather than a subcolumn of the source part.

What is fixed:

  • Skip index over a subcolumn — rebuilt on ALTER MODIFY COLUMN, ALTER UPDATE, ALTER CLEAR COLUMN, MATERIALIZE TTL and patch updates of the column, with all of its other inputs (t.a + y). The partial-rewrite path (MutateSomePartColumns) no longer fails with NOT_FOUND_COLUMN_IN_BLOCK.
  • Projection — rebuilt when the altered column feeds its sort key (a subcolumn sort key was missed; for an aggregate projection its GROUP BY expressions) or its WHERE clause. Both decide what the projection stores. A column used only in its SELECT needs no rebuild, because it is converted on read.
  • alter_column_secondary_index_mode — the throw guard in checkAlterIsPossible also fires for an explicit index over a subcolumn of the altered column, instead of accepting the ALTER and failing or dropping the index during the mutation.
  • TTL over a subcolumn — recalculated when its column is mutated, so rows and columns whose TTL moved into the past expire. The TTL infos stored in parts keep the name of the original expression, so parts written by older versions still match their rule.
  • MATERIALIZED column — recalculated when ALTER MODIFY COLUMN changes the type of a column it reads (directly, through a subcolumn, an ALIAS or another MATERIALIZED column), and everything depending on it is rebuilt too. A conversion that keeps the stored bytes but changes the values read (Enum8 -> Int8) now runs a mutation when such a column exists; adding values to an Enum stays metadata-only.
  • Key MATERIALIZED column — a MATERIALIZED column in a key (or a subcolumn of it in the key), or used as the version column, cannot be recalculated in an existing part, which is also why MATERIALIZE COLUMN refuses key columns. Changing the type of a column it is computed from, including an ALIAS, is now rejected with ALTER_OF_COLUMN_IS_FORBIDDEN, because even a conversion that keeps the values of the source can change it (toTypeName(x)). The check runs only for the initial execution of an ALTER in a Replicated database, so a replica does not reject an entry the initiator committed.

Reproductions, all silent wrong results before this PR:

-- skip index on a subcolumn
CREATE TABLE t (id UInt32, t Tuple(a Int32, b String), INDEX idx t.a TYPE minmax GRANULARITY 1)
ENGINE = MergeTree ORDER BY id
SETTINGS index_granularity = 4, min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO t SELECT number, (number, 'x') FROM numbers(16);
ALTER TABLE t MODIFY COLUMN t Tuple(a Float32, b String);
SELECT count() FROM t WHERE t.a >= 1;                             -- 0 before, 15 now
SELECT count() FROM t WHERE t.a >= 1 SETTINGS use_skip_indexes=0; -- 15, ground truth

-- projection filtered on a column whose type changes
CREATE TABLE t2 (id UInt64, x Int64, PROJECTION p (SELECT sum(id) WHERE x < 0))
ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 0;
INSERT INTO t2 SELECT number, toInt64(3000000000) + number FROM numbers(100);
ALTER TABLE t2 MODIFY COLUMN x Int32;  -- every value wraps negative, so WHERE x < 0 now matches all rows
SELECT sum(id) FROM t2 WHERE x < 0;    -- 0 before, 4950 now

-- MATERIALIZED column computed from a column whose type changes
CREATE TABLE t3 (x Int64, m Int64 MATERIALIZED x) ENGINE = MergeTree ORDER BY tuple()
SETTINGS min_bytes_for_wide_part = 0;
INSERT INTO t3 VALUES (5000000000);
ALTER TABLE t3 MODIFY COLUMN x Int32;
SELECT x, m FROM t3;  -- 705032704, 5000000000 before; 705032704, 705032704 now

Tests: 04617_stale_subcolumn_skip_index_after_mutation (indexes, projections and TTL over subcolumns), 04840_recalculate_materialized_column_on_source_type_change (recalculation of MATERIALIZED columns) and 05845_alter_type_of_key_materialized_source (rejected type changes under key MATERIALIZED columns).

Known gaps left for follow-up pull requests, all reproducible on master: a subcolumn in a projection WHERE is accepted at CREATE but fails at INSERT (Not found column t.a in block); the aggregation assignments of a GROUP BY TTL are not covered by the rewrite; a TTL is not recalculated on a metadata-only conversion; changing the type of an ALIAS column does not recalculate a non-key MATERIALIZED column computed from it.

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 wrong query results caused by a mutation leaving data derived from the mutated column stale on wide parts. A skip index or a TTL expression defined on a subcolumn (for example a Tuple, Nested, Map or JSON element) is now rebuilt or recalculated when ALTER MODIFY COLUMN, ALTER UPDATE or ALTER CLEAR COLUMN changes the parent column; a projection is rebuilt when the altered column feeds its sort key or its WHERE clause; and a MATERIALIZED column is recalculated when ALTER MODIFY COLUMN changes the type of a column it is computed from. An ALTER MODIFY COLUMN of a column that a MATERIALIZED column in the sorting or partition key (or the version column) is computed from is now rejected, because such a column cannot be recalculated in an existing part.


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

`ALTER TABLE ... MODIFY COLUMN <parent>` that changes the on-disk
representation of a subcolumn (e.g. a `Tuple`/`Nested`/`Map`/`JSON`
element) did not rebuild a skip index defined on that subcolumn when the
table uses wide parts. `MutationsInterpreter::prepare`, in the
`READ_COLUMN` branch, decided whether an index must be rebuilt by
comparing the mutated column name against the index's required columns
with exact string equality: for an index on `t.a` and
`ALTER ... MODIFY COLUMN t ...` the required column is `t.a` while
`command.column_name` is `t`, so the comparison never matched. The index
was neither rebuilt nor dropped, and on a wide part the unchanged
`skp_idx_*` files were hardlinked into the mutated part, leaving the
index holding bytes serialized under the old subcolumn type. Depending on
the index type this produced silent wrong results, `CANNOT_READ_ALL_DATA`
or `MEMORY_LIMIT_EXCEEDED`.

Resolve each required column to the column it is stored in (via
`getNameInStorage`) before comparing to the altered column name, mirroring
the existing subcolumn-aware checks in
`MergeTreeData::checkAlterIsPossible` and
`MutationsInterpreter::validateUpdateColumns`.

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

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7b3c2b0]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
Stateless tests (amd_debug, ParallelReplicas, s3 storage, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
05595_timeseries_external_targets_truncate NOT_FAILED cidb
05059_promql_empty_by_group NOT_FAILED cidb
05019_group_by_top_k_compatibility NOT_FAILED cidb
05320_promql_duplicate_series_one_to_one_matching NOT_FAILED cidb
05234_promql_result_timestamp_type NOT_FAILED cidb
05033_lazy_materialization_column_function_structure_equals NOT_FAILED cidb
05137_join_fixed_string_zero_bytes_runtime_filter NOT_FAILED cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
05293_promql_constant_scalar_arithmetic NOT_FAILED cidb
19 more test cases not shown

AI Review

Summary

Reviewed #112717 at 7b3c2b0320ffb7bf49947ee91390a7349589d572, including all 36 discussion threads and their replies. The PR repairs mutation dependency tracking for subcolumns and aliases, rebuilds affected indices and projections, recalculates TTLs and stored MATERIALIZED columns, and rejects changes affecting immutable materialized keys. No new inline finding remains after tracing the current code. Six previously dismissed correctness findings still hold and are retained below; their threads remain untouched.

Findings

❌ Blockers

  • src/Storages/AlterCommands.cpp:1720 — An altered alias can leave stored dependents stale. [dismissed by author -- https://github.com/Rebuild skip indices, projections, TTL and MATERIALIZED columns left stale by ALTER MODIFY / UPDATE / CLEAR COLUMN #112717#discussion_r4670929304] The scheduling loop still considers only physical columns. With x Int64, a Int64 ALIAS x, m Int64 MATERIALIZED a % 1000, and x = 5000000001, changing a to Int32 schedules no recomputation: a % 1000 becomes 705 while stored m remains 1. The key guard now rejects the immutable-key case, but this non-key case remains. Schedule work for stored alias dependents, or link a dedicated follow-up issue and document the required MATERIALIZE COLUMN repair.

  • src/Interpreters/MutationsInterpreter.cpp:921; src/Storages/MergeTree/MutateTask.cpp:938,1324,4858 — Recomputation still depends on whether the source itself is rewritten. [dismissed by author -- https://github.com/Rebuild skip indices, projections, TTL and MATERIALIZED columns left stale by ALTER MODIFY / UPDATE / CLEAR COLUMN #112717#discussion_r4643082513] A Variant extension is skipped before dependency analysis, leaving a materialized toTypeName result unchanged. After CLEAR COLUMN x, an absent source without a marker also loses its READ_COLUMN command: converting cleared FixedString(3) to String leaves m MATERIALIZED hex(x) at '000000' although hex(x) is empty. These filters remain in both part paths. Schedule dependent work independently of source rewriting, or explicitly track these two omissions.

  • src/Storages/AlterCommands.cpp:1726 — Metadata-only logical conversions leave TTL bounds stale. [dismissed by author -- https://github.com/Rebuild skip indices, projections, TTL and MATERIALIZED columns left stale by ALTER MODIFY / UPDATE / CLEAR COLUMN #112717#discussion_r4643710440] The new scheduling decision checks only materialized dependents. For x Date with TTL toDateTime(x) + INTERVAL 1 DAY, changing x to UInt16 reinterprets a stored date such as '2030-01-01' as seconds after the epoch, but creates no mutation and retains the old future expiry. Expired data remains eligible for retention until that old bound. Include affected TTLs in scheduling, or link a dedicated follow-up issue.

  • src/Interpreters/MutationsInterpreter.cpp:1243; src/Storages/TTLDescription.cpp:1503 — TTL invalidation misses dependencies removed by constant folding. [dismissed by author -- https://github.com/Rebuild skip indices, projections, TTL and MATERIALIZED columns left stale by ALTER MODIFY / UPDATE / CLEAR COLUMN #112717#discussion_r4643710448] TTL dependencies still come from executable required columns, rather than the semantic resolver added for indices and materialized columns. For TTL d + INTERVAL if(toTypeName(x) = 'Int64', 5000, 0) DAY, changing x from Int64 to Int32 leaves the old future TTL bounds even when the new expiry is past. Collect semantic timestamp and predicate dependencies, or explicitly track this omission.

  • src/Interpreters/MutationsInterpreter.cpp:1750 — Batched conversions still expose later source conversions to an intervening update. [dismissed by author -- https://github.com/Rebuild skip indices, projections, TTL and MATERIALIZED columns left stale by ALTER MODIFY / UPDATE / CLEAR COLUMN #112717#discussion_r4670213681] For m MATERIALIZED x + z % 1000, queue conversion of x, then UPDATE y = m, then conversion of z. Recomputing m at the first command already reads z at its final type. With (x, z) = (1, 5000000001), the discussed batch stores y = 706, whereas serial execution stores y = 2. The final m is repaired, but the intervening result remains wrong. Preserve command-boundary semantics, prevent such coalescing, or link a dedicated issue covering the shared-source case. The existing regression tests only the case where m reads the later source alone.

  • src/Interpreters/MutationsInterpreter.cpp:1750 — Generated materialized recomputation bypasses replica determinism validation. [dismissed by author -- https://github.com/Rebuild skip indices, projections, TTL and MATERIALIZED columns left stale by ALTER MODIFY / UPDATE / CLEAR COLUMN #112717#discussion_r4680733943] A source type change recomputes m MATERIALIZED rand64() + toUInt64(x) independently on each replica even with allow_nondeterministic_mutations = 0. Validation still inspects explicit mutation expressions and virtual-column references, not the generated dependency expressions, so replicas can produce different checksums and require reconciliation downloads. This remains real, but the shared validation defect is tracked by The Replicated mutation determinism guard misses a non-deterministic function hidden in an ALIAS or recomputed MATERIALIZED column — replicas mutate divergently and reconcile by first-committer-wins download #122281. Extend that fix and its rejection coverage to this new type-change path.

Missing context / blind spots
  • ⚠️ No ClickHouse binary is available in this review job, so the retained examples were verified against current source paths and the prior discussion evidence, not rerun locally. Mixed-version DDL replay was also assessed from source; an upgrade regression would provide runtime evidence.
Tests
  • ⚠️ The retained cases need focused regression coverage alongside their fixes: alias-only type changes, skipped or absent source columns, metadata-only and folded TTL dependencies, and a batched materialized expression reading both converted sources. The determinism tracker should cover rejection of the generated type-change recomputation on a replicated table.

The current head's Fast test report passes 04617_stale_subcolumn_skip_index_after_mutation, 04840_recalculate_materialized_column_on_source_type_change, and 05845_alter_type_of_key_materialized_source. The fetched CI reports contain no failed tests. No nested CI run was started.

Final Verdict

Status: ❌ Block

Before approval, fix the remaining untracked stale-data and command-order cases, or link dedicated follow-up issues explicitly covering them and the narrowed contract. The nondeterminism defect already has a tracker. No new inline comments were posted, and no existing thread was replied to, resolved, or reopened.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 31, 2026
Extend the fix to the remaining mutation paths that could leave a skip
index on a subcolumn (e.g. `t.a`) stale when the parent column `t` is
mutated as a whole.

Instead of comparing raw required-column names, resolve an index's
required columns by rewriting subcolumns to `getSubcolumn` (the same
rewrite already used for `MATERIALIZED` expressions in
`replaceSubcolumnsToGetSubcolumnFunctionInQuery`) so the required columns
become top-level columns. This makes a mutation of the parent recognized
as affecting the index in the `MODIFY COLUMN`, `UPDATE`, `CLEAR COLUMN`
and patch-update paths.

The recomputation itself is fixed the same way: in the
`MutateSomePartColumns` path the index expression is rewritten to read the
updated whole column and extract the subcolumn via `getSubcolumn`, instead
of failing with `NOT_FOUND_COLUMN_IN_BLOCK` or recomputing the index from a
stale pre-extracted subcolumn read from the source part.

Add `UPDATE` and `CLEAR COLUMN` cases to the test.

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

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

Avogar and others added 2 commits August 5, 2026 13:55
…n indices

Extend the subcolumn-aware handling to the remaining places that compare an
expression's required columns against the mutated column, addressing the
review feedback:

- Share a single `getSubcolumn`-based helper
  (`getRequiredColumnsWithSubcolumnsReplaced`) that returns an expression's
  required columns resolved to their top-level columns, and use it from
  `MutationsInterpreter` (skip index checks) instead of a local copy.

- Projections: an `ALTER MODIFY COLUMN t` that changes the type of a subcolumn
  used in a projection's sort key (e.g. `ORDER BY t.a`) now rebuilds the
  projection. Otherwise the projection's own primary index (which stores the
  sort key as raw bytes) was hardlinked stale and mis-pruned granules on wide
  parts, returning wrong results.

- `MergeTreeData::checkAlterIsPossible`: key `columns_in_explicit_indices` by
  the top-level column so `alter_column_secondary_index_mode = 'throw'/'compatibility'`
  rejects an ALTER of the parent of a subcolumn index synchronously, instead of
  silently dropping/rebuilding the index later during the mutation.

- TTL: a TTL expression on a subcolumn (e.g. `TTL t.a`) is now recalculated
  when the parent column is updated, and is evaluated from the updated parent
  via `getSubcolumn`. The subcolumns are rewritten when deriving
  `expression_columns` and when building the expression for execution, so both
  dependency tracking (`getColumnDependencies`) and recomputation are fixed;
  the stored TTL AST is kept unchanged for `SHOW CREATE`.

Extend the test with projection, throw-mode and TTL cases.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Avogar and others added 3 commits August 6, 2026 19:06
The READ_COLUMN projection check only rebuilt a projection when the altered
column fed the projection's primary/sort key. A projection may also depend on a
column through its WHERE clause (e.g. an aggregate projection
`SELECT sum(id) WHERE x < 0`), and the WHERE decides which rows/groups are stored
at build time. An `ALTER MODIFY COLUMN` that changes the column's type so the
filter result flips (e.g. `Int64 -> Int32` wrapping positive values negative)
then leaves the projection hardlinked unchanged on wide parts, so the stale
aggregate/subset is served and queries return wrong results.

Extend the check to also match the projection's WHERE-clause columns (resolving
subcolumns via getSubcolumn, like the key columns). SELECT outputs are still not
checked: they are read back with an on-the-fly type cast and stay consistent.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…:ClickHouse/ClickHouse into fix-stale-subcolumn-skip-index-after-mutation
…olumn

ALTER MODIFY COLUMN never consulted the source column -> MATERIALIZED column map, so a
conversion that changes values left every dependent MATERIALIZED column holding values
computed from data the mutation had just rewritten, while ALTER UPDATE of the same column
recalculates them. Recalculate them in a stage after the one that reads the columns at
their new type (chained MATERIALIZED columns ordered after each other), and let them enter
dependency analysis so skip indices, projections, TTL and statistics defined on them are
rebuilt too.

A MATERIALIZED column that is part of a key cannot be recalculated in place, because the
sort order and the partition id are fixed when the part is written - which is also why
MATERIALIZE COLUMN refuses key columns. Reject such an ALTER in checkAlterIsPossible
unless the conversion preserves values, instead of silently leaving the key inconsistent
with its expression and unrepairable.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7b3c2b032 with master 5300a7cf7 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c6058ac56; 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

9 object files changed (+204.16 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/expressionSourceColumns.cpp.o new 118.54 KiB +118.54 KiB
src/CMakeFiles/dbms.dir/Interpreters/MutationsInterpreter.cpp.o 1.07 MiB 1.15 MiB +84.28 KiB (+7.70%)

716 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

265 translation units recompiled, 2250 s compile time in total, 264 of them have a recent master baseline.

Job report

@Avogar Avogar changed the title Rebuild subcolumn skip index on ALTER MODIFY COLUMN of the parent Rebuild skip indices, projections, TTL and MATERIALIZED columns left stale by ALTER MODIFY / UPDATE / CLEAR COLUMN Aug 13, 2026
Dependencies of an index, a projection, a TTL or a MATERIALIZED column were resolved by
comparing raw names, so an expression reading an ALIAS column was keyed under the alias
instead of the columns it reads. ALTER MODIFY COLUMN of such a column then failed the
mutation with UNKNOWN_IDENTIFIER, because an ALIAS cannot be read from a part, and an
ALTER of a MATERIALIZED key column derived through an ALIAS was not rejected.

Resolve every one of those expressions with the query analyzer instead, moving the
resolver ClickHouse#112302 already had in MergeTreeData into a shared unit. It returns the columns
an expression reads, not getSelectedColumnsNames(), which reports an ALIAS column under
its own name; subcolumns come back as columns of their own, so callers fold them into the
column they are stored in. This drops the TreeRewriter usage added for these checks and
two more that master had.

The same accessor fixes the lazy JSON type hint guard: it consulted the analyzer for
MATERIALIZED expressions and so missed a column reading a changed JSON path, accepting a
metadata-only ALTER that leaves that column stale with no mutation able to recompute it.

A MATERIALIZED column is also recomputed in a stage that runs after the columns are read
at their new type, with ALIAS columns substituted, so it does not depend on which analyzer
builds the stage expression.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@groeneai groeneai mentioned this pull request Aug 14, 2026
1 task done
The key of an aggregate projection is built over the projection's own columns: `GROUP BY
f(x)` becomes the key `f(x)`. Resolving that key against the table columns does not find
them, so `ALTER TABLE ... MODIFY COLUMN x ...` failed the mutation with UNKNOWN_IDENTIFIER
for a projection like `SELECT toStartOfMinute(ts), count() GROUP BY toStartOfMinute(ts)`.

Take the group expressions from the projection query instead, which are written in terms of
the table columns. A normal projection keeps using its primary key, whose columns are the
table columns.

An ALTER that would change the group values is refused earlier because the type of the
projection's key column cannot be converted, so this decides the rebuild only for
conversions that keep them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Avogar and others added 3 commits August 27, 2026 14:20
Master grew a shared dependency graph over MATERIALIZED columns and, in
MutationsInterpreter, a transitive closure plus level-ordered recompute stages for UPDATE,
APPLY PATCHES and CLEAR COLUMN. This branch had its own version of all three for
ALTER MODIFY COLUMN, so drop them: the columns read at another type get their closure from
affected_materialized_closure, join all_affected_materialized, and are recomputed by
emit_materialized_recompute_stages after the stage that reads them at the new type.

makeMaterializedColumnExpression stays for MATERIALIZE COLUMN, which also accepts a DEFAULT
column and so is not covered by the graph.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The graph resolved a default with TreeRewriter, the analyzer ClickHouse is moving away from.
Ask the analyzer instead, through the same helper the index, projection and key checks use,
so every dependency in a mutation is resolved one way.

The ALIAS substitution and the getSubcolumn rewrite still apply to the stored expression,
which the recompute stage evaluates; only the name resolution moved.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Avogar and others added 3 commits November 17, 2026 23:48
…mn-skip-index-after-mutation

# Conflicts:
#	src/Interpreters/MutationsInterpreter.cpp
#	src/Storages/MergeTree/MergeTreeData.cpp
#	src/Storages/MergeTree/MutateTask.cpp
#	src/Storages/TTLDescription.cpp
Two issues introduced while merging master into the branch:

- The anonymous namespace was left unclosed after combining the branch's
  `makeMaterializedColumnExpression` with master's
  `getColumnsRequiredToRecalculateTTL`, which pulled `getAllColumnDependencies`
  into the unnamed namespace and broke its external linkage (it is declared in
  the header and used by MutateTask.cpp). Restore the closing brace.

- master changed the `emit_materialized_recompute_stages` lambda to take a
  `mutation_version` argument; the branch's type-changed MATERIALIZED call site
  was not updated by the merge. Pass `std::nullopt`, matching the sibling patch
  and clear-column call sites.

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

- `replaceSubcolumnsToGetSubcolumnFunctionInQuery` split an identifier only at
  its first dot, so a subcolumn of a column whose own name contains a dot
  (`a.b.x` of column `a.b`, next to a column `a`) was never rewritten to
  `getSubcolumn`. The index recalculation of a mutation then failed with
  `NOT_FOUND_COLUMN_IN_BLOCK` (test 05029, case added on master). Try every
  split point, like `Block::findSubcolumnByName`.

- Drop the redundant `static` of `makeMaterializedColumnExpression`, which is
  now inside an anonymous namespace (clang-tidy).

- 05294: the full mutation now recomputes the MATERIALIZED column read through
  an ALIAS, so the reference gets the recomputed value, the same as for a
  direct reference.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112717&sha=18a714ac3f5003b9036d6ea7c640f9a8267b0074&name_0=PR
ClickHouse#112717

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
…olumn type change

Three issues found in review of the subcolumn mutation handling:

- Recalculating a skip index whose expression reads a subcolumn (e.g. `t.a + 1`)
  renamed the index output to the `getSubcolumn` form, so it no longer matched
  `IndexDescription::column_names` and the mutation failed with
  NOT_FOUND_COLUMN_IN_BLOCK. Build the recalculated index expression the same way
  the whole-part path does (`getSkipIndicesExpression` plus
  `createSubcolumnsExtractionActions`): the subcolumn is extracted from the parent
  the stream carries while the expression keeps its original output name.

- A MATERIALIZED column reached through a sorting/partition-key subcolumn
  (`ORDER BY m.a`, `m MATERIALIZED tuple(x)`) was not recognised as a key column,
  so a value-changing `MODIFY COLUMN` of its source was accepted and left a stale
  primary index. Include the stored parents of key subcolumns in the guard, and
  resolve key columns to their storage columns in the recomputation path too.

- A type change was not detected for a column stored only as a missing-column
  marker (`skip_empty_columns_on_insert`), because `tryGetColumn` returns null,
  so a dependent MATERIALIZED column kept stale values. Resolve the old type from
  the serialization infos, like the READ_COLUMN projection/index path already does.

Also drop a redundant string_view->String conversion flagged by clang-tidy.

Tests: 05828 (expression index on a subcolumn), 05829 (materialized key subcolumn),
05830 (missing-column marker type change).

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Second review round on the subcolumn mutation handling:

- Rebuilding a skip index on a subcolumn plus another column (`t.a + y`) read
  only the mutated column, not `y`, so the recalculation failed with
  NOT_FOUND_COLUMN_IN_BLOCK. getColumnDependencies compares an index's inputs by
  raw name and misses that a mutation of the parent `t` affects an index on
  `t.a`, so the index's other inputs never entered the read set. Resolve each
  index's required columns to their storage columns and, when the mutation
  touches any of them, read all of them.

- expressionSourceColumns missed a dependency hidden by constant folding: the
  analyzer rewrites a type-dependent function such as `toTypeName(x)` to a
  constant whose source expression (referencing `x`) is not a child node, so the
  read set omitted `x` and a dependent MATERIALIZED column kept stale bytes.
  Also traverse the source expressions of folded constants.

- The materialized-key guard did not cover a MATERIALIZED column used as the
  engine's sign/version column outside the sorting/partition key, so a
  value-changing ALTER of its source was accepted while the recomputation path
  (getKeyColumns) excluded it. Include sign/version columns in the guard.

Tests: 05831 (index on a subcolumn plus another column), 05832 (type-dependent
materialized expression), 05833 (materialized version column).

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Storages/TTLDescription.cpp Resolved
Avogar and others added 2 commits November 19, 2026 20:46
…umn guard

- expressionSourceColumns collected a ColumnNode purely by name, so a lambda
  argument that shadows a table column (`arrayMap(x -> x + 1, ...)`) was recorded
  as a dependency on the stored column `x`, wrongly rejecting a MODIFY of `x`.
  Require the column's source to be the analyzed table, like
  CollectSourceColumnsVisitor skips lambda-argument sources.

- The materialized sign/version guard compared the column name directly with
  merging_params.sign_column/version_column, missing a version column that is a
  subcolumn (`ReplacingMergeTree(m.v)`, `m MATERIALIZED tuple(x)`): `m` != `m.v`,
  while recomputation normalizes `m.v` to `m` and skips it. Resolve the sign and
  version columns to the columns they are stored in before comparing.

Tests: 05834 (lambda argument shadowing a table column), 05835 (materialized
version column used through a subcolumn).

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ecalc on metadata-only conversions

- A TTL on a subcolumn is executed through the `getSubcolumn` rewrite, but its
  result was named after the rewritten expression, and that name is
  `result_column`, the key of the TTL infos stored in parts. Parts written
  before the rewrite (`ts.d + toIntervalDay(1)`) then no longer matched their
  recompression/move rule. Name the result after the original expression at all
  four rewrite sites (TTL expression and WHERE, at analysis and at rebuild).

- The guard for a MATERIALIZED column that is part of a key let a type change of
  its source through when `isSafeForKeyConversion` held. That proves the source
  keeps its values, not that the key column does: `m MATERIALIZED toTypeName(x)`
  changes with the type. The key column cannot be recalculated in an existing
  part, so reject any type change of a column it is computed from.

- A conversion that changes only metadata (`Enum8 -> Int8`, `DateTime -> UInt32`,
  `Date -> UInt16`) emitted no mutation, so a MATERIALIZED column computed from
  the column kept its old value. Schedule a mutation in that case; it then
  recalculates the column (or the key guard rejects the ALTER). Restating the
  same type and adding values to an Enum stay metadata-only.

Tests: 05836 (stored TTL name), 05837 (metadata-only conversions), 04840 case 6
(type change under a MATERIALIZED key column is rejected, incl. `toTypeName`).

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
`checkAlterIsPossible` returned early for the engine version column after
validating its own conversion, so the check rejecting a type change of a
column that a key MATERIALIZED column is computed from never ran for it.
With `ReplacingMergeTree(v)` and `m MATERIALIZED toTypeName(v)` in the
sorting key, `MODIFY COLUMN v UInt64` was accepted and left `m` stale. Move
the check into a lambda and also run it before that early exit.

Test: 05838.

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
…MATERIALIZED columns

- For an index on `t.a + y`, an UPDATE of both `t` and `y` made the raw index
  inputs add `t.a` to the read set through `y`. The stream then carried a `t.a`
  read from the source part next to the updated `t`, and the index was rebuilt
  from the stale subcolumn. Read the storage column of a subcolumn index input
  instead, so the subcolumn is extracted from the updated value.

- When one ALTER changes the type of a source and of a MATERIALIZED column
  computed from it, the closure skipped the MATERIALIZED column because it was
  among the converted columns, so only its stored value was cast. Recompute it
  too when one of its inputs is converted or recomputed.

Tests: 05839, 05840.

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Avogar and others added 2 commits November 23, 2026 16:13
…HEMERAL columns

The guard decided whether a key MATERIALIZED column depends on the altered
column with `findColumnsToRecalculate`, which deliberately returns nothing for
a column reading an EPHEMERAL one, because such a column is never recalculated.
So `m MATERIALIZED if(e, toTypeName(x), '')` in the sorting key let
`MODIFY COLUMN x Int32` through and kept a stale key. Add
`MaterializedColumnDependencies::dependsOn`, a transitive walk over the
dependencies that does not stop at EPHEMERAL readers, and use it in the guard.

The guard also ran only for an ALTER that needs a mutation, so a metadata-only
conversion (`Enum8 -> Int8`) of the source of such a column skipped it. Run it
for every MODIFY COLUMN.

Test: 05841.

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A column TTL on `t` makes MATERIALIZE TTL reset `t`, and the final index
selection, which resolves subcolumns to their storage columns, then rebuilds an
index on `t.a + y`. But the TTL branch collected the index inputs with the raw
name comparison of getColumnDependencies, which does not match `t.a` against
`t`, so `y` was not read and the mutation kept failing with
NOT_FOUND_COLUMN_IN_BLOCK. Before this PR the index was not selected at all,
so it was carried over stale.

Turn the subcolumn-aware pass that adds all inputs of an affected index (and
reads the storage column of a subcolumn input) into a lambda, and also call it
for the columns the TTL resets.

Test: 05842.

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…es of MATERIALIZED keys

- An UPDATE of a TTL source (`d`) makes the dependency collection add the TTL
  target (`t`) to the written columns, and the final index selection then
  rebuilds an index on `t.a + y`. The subcolumn-aware pass that adds the index's
  other inputs got only the directly updated columns, so `y` was not read and
  the mutation failed with NOT_FOUND_COLUMN_IN_BLOCK. Pass it every column the
  mutation writes.

- MATERIALIZED columns depending on a converted column were recomputed after all
  commands of the mutation, so a batched later `UPDATE y = m` read the old `m`
  and produced a different result than running the two mutations one after the
  other. Emit those stages at the first type-change command; the source is
  converted when it is read, so they already see its new values.

- Changing the type of an ALIAS column changes its value, but the guard for
  MATERIALIZED key columns looked only at physical columns, and the dependency
  graph expands aliases to the columns they read. For an ALIAS, take its old
  type from the description and walk the original expressions of ALIAS and
  MATERIALIZED columns to find a key column reading it.

Tests: 05842 (ordinary UPDATE of the TTL source), 05843, 05844.

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Storages/AlterCommands.cpp Resolved
…bdas in the alias guard

- The first type-change command of a batched mutation recomputed the
  MATERIALIZED dependents of every conversion in the batch, so an UPDATE between
  two conversions read values derived from the later one. Recompute the
  dependents of each converted column at its own command.

- The ALIAS check of the MATERIALIZED-key guard looked up an identifier such as
  `m.v` as a whole column name and stopped, missing an alias read by `m`.
  Resolve a subcolumn to the column it belongs to before following that
  column's definition.

- The same walk treated a lambda parameter named like the alias as a reference
  to it and rejected a valid alteration. Skip lambda parameters inside the
  lambda body.

Tests: 05843 (two conversions around an UPDATE), 05844 (alias through a
subcolumn, lambda parameter shadowing the alias).

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ore alias prefixes

- A `Replicated` database re-executes a committed ALTER on every replica. The
  MATERIALIZED-key guard and the subcolumn-aware index columns of
  `alter_column_secondary_index_mode = 'throw'` are newer than an initiator of
  an older version, so a replica could refuse an entry the initiator committed
  and retry it forever. Apply them only to the initial execution, like the
  neighboring restrictions (`isSecondaryDDLReplay`); a replay keeps the raw index
  column names.

- The ALIAS check took any identifier starting with `a.` as a subcolumn of the
  alias `a`, so a stored column literally named `a.v` made the guard reject a
  valid ALTER. Resolve the identifier in the table first and use the prefix
  only for a name that does not resolve.

Test: 05844 (stored `a.v` next to the alias `a`).

ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
On object storage the TRUNCATE removed the mutated part inside the query, and a
pre-existing issue (files of a column expired by TTL left in a mutated part but
not in its checksums) made that removal log CANNOT_RMDIR before falling back to
a recursive removal. The error reached the client's stderr and failed the test
in the private sync (flaky check, s3 storage, meta in keeper). Run the second
case on its own table, so no part is removed inside a query.

https://d1k2gkhrlfqv31.cloudfront.net/clickhouse-test-reports-private/praktika.html?PR=89494&sha=888bf9346c5cbe1e1cb81537c10b41ff49fefd5e&name_0=PR
ClickHouse#112717

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- Replace the hand-written `reads_alias` AST walker with
  `expressionReadsColumn`, which uses the query analyzer; `dependsOn`
  handles an ALIAS source.
- Add `MergeTreeData::getStorageColumnsFixedInPart` (keys plus sign and
  version columns, resolved to storage) and use it in
  `validateUpdateColumns`, `prepare` and `checkAlterEligibility`.
- Resolve the storage columns of each skip index once per `prepare`.
- `isTrueMetadataOnlyConversion` reports whether values are
  reinterpreted, replacing the Enum/container special case.
- `buildTTLExpressionAndSets` replaces four copies of the subcolumn
  rewrite of TTL expressions.
- Compact comments; merge 17 small tests into 04617, 04840 and the new
  05845.

Co-Authored-By: Claude Opus 5.5 <[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

comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). 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