Skip to content

Fix a stuck mutation after MODIFY COLUMN from Nullable with a DEFAULT that reads another column - #124561

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:modify-column-null-default-reads-other-columns
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:modify-column-null-default-reads-other-columns

Conversation

@groeneai

@groeneai groeneai commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #84770

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 ALTER TABLE ... MODIFY COLUMN from a Nullable type to a non-Nullable type with a DEFAULT that reads another column, for example MODIFY COLUMN a Int64 DEFAULT c0 + 100: the mutation never finished (UNKNOWN_IDENTIFIER) and every read of the column failed, even after KILL MUTATION.

Description

On 26.8.18.2 and 26.3.42.3, ALTER TABLE t MODIFY COLUMN a Int64 DEFAULT c0 + 100 of a Nullable(Int64) column is accepted, but its mutation never finishes (Code: 47 Unknown expression or function identifier c0) and every SELECT of a fails the same way. KILL MUTATION does not help.

Since #84770 the reader converts such a column with if(isNull(a), <DEFAULT>, assumeNotNull(a)), but it evaluates that on a block holding only the converted columns and never reads the columns the DEFAULT refers to. The ALTER-time check uses the full old header and passes.

The reader now does for this conversion what it already does for the DEFAULT of a missing column:

  • injectRequiredColumns also reads the columns the DEFAULT of such a column refers to;
  • performRequiredConversions gets the row's other columns as extra inputs, only when a step converts NULLs through a DEFAULT: those of this read step, and those of earlier steps only when no patch part or on-fly mutation newer than the ALTER exists (they may hold values written after it);
  • the conversion is resolved with prefer_column_name_to_alias = 0, so a DEFAULT reading a column that is converted too reads its converted value under any profile (with 1 it read the old one).

Known limitations: a DEFAULT reading a column the old part does not store (added later and not materialized) still fails as before (MATERIALIZE COLUMN first works around it); after a lightweight UPDATE issued while the mutation is pending, a read whose PREWHERE reads the dependency fails as before until the mutation finishes.

The new test fails on master and covers Compact and Wide parts, reads before the mutation (with PREWHERE and lazy materialization), MATERIALIZED and converted dependencies, patch parts before and after the ALTER and LowCardinality(Nullable(String)); 50 randomized runs pass.

🤖 Generated with Claude Code


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

groeneai and others added 3 commits October 8, 2026 03:55
…he row

Converting a column from `Nullable` to a non-`Nullable` type replaces NULLs
with the column's DEFAULT (ClickHouse#84770). The reader evaluated that expression on a
block holding only the converted columns, and did not read the columns the
DEFAULT refers to, so `MODIFY COLUMN a Int64 DEFAULT c0 + 100` was accepted,
its mutation failed forever with UNKNOWN_IDENTIFIER `c0`, and every read of
`a` failed until the ALTER was undone.

Mirror what the reader already does for the DEFAULT of a missing column:
- `injectRequiredColumns` also reads the columns the DEFAULT of such a column
  refers to;
- `performRequiredConversions` gets the other columns of the same rows (this
  read step and the previous steps of the chain) as extra inputs;
- the conversion is resolved with `prefer_column_name_to_alias = 0`, so a
  DEFAULT reading another column that is converted too reads the converted
  value whatever the server profile says.

A DEFAULT reading a column the old part does not store (added later and not
materialized) still fails as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ALTER

A previous read step can hold a value written after the pending
`ALTER MODIFY COLUMN`: a patch part newer than the ALTER is applied after
conversions in the step that reads its column, and an on-fly mutation newer
than the ALTER overwrites its target columns. Feeding such a value to the
NULL->DEFAULT conversion of a later step made the result depend on PREWHERE
placement: after `UPDATE t SET c0 = c0 + 10`, `SELECT c0, a` returned
`(11, 101)` while `SELECT a ... PREWHERE c0 > 0` returned `111`.

Pass the previous steps' columns to the conversion only when the chain has no
patch part and no on-fly mutation newer than the ALTER. Otherwise a DEFAULT
dependency read by an earlier step fails with UNKNOWN_IDENTIFIER, as before,
until the mutation finishes; dependencies read by the same step, and the
mutation itself, are unaffected.

The test also asserts that the lazy materialization case is really lazy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop three comments that restate the name they sit above, and restore an unchanged master comment line.

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 8, 2026
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (2 rounds, 6 findings; click to expand)

Pre-publication review by an independent model (engine: codex) plus my own review of the code.

# Sev Finding Verdict Evidence / action
1 ⚠️ A DEFAULT dependency read by an earlier step could hold a value written after the pending ALTER (a later lightweight UPDATE), so the result depended on PREWHERE placement AGREE, fixed @ 00b9633 earlier steps are used only when no patch part or on-fly mutation newer than the ALTER exists; test case added
2 ⚠️ The lazy-materialization case did not prove the rewrite happened AGREE, fixed @ 00b9633 EXPLAIN check for LazilyReadFromMergeTree added
3 ❌ After KILL MUTATION, a lightweight UPDATE made before the ALTER is applied after the conversion ((11, 101), not (11, 111)), and a patch that updated the column still fails DISAGREE KILL MUTATION removes the ALTER version that orders patches against the conversion for every reader (AlterConversions.cpp:273), so the merge that later rewrites the part stores the same (11, 101) the read returns; the second case fails the same way on master (patch-reader conversion, unchanged here)
4 ❌ A subcolumn of a converted Nullable(Tuple) (x.a) reads the type default instead of the DEFAULT DISAGREE, out of scope the subcolumn conversion looks the DEFAULT up by the subcolumn name (inplaceBlockConversions.cpp:192), so master returns the same value with a constant DEFAULT; unrelated to reading other columns
5 💡 On-fly mutation steps older than the ALTER still convert without the rest of the row noted loud error as before, apply_mutations_on_fly only
6 💡 inplaceBlockConversions.h now includes Core/Block.h for a default argument noted its includers already use Block

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

Session id: cron:clickhouse-review-self-slot-58:20261008-065200

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE y (c0 Int64, a Nullable(Int64)) ENGINE = MergeTree ORDER BY tuple(); INSERT INTO y VALUES (1, NULL), (2, 5); ALTER TABLE y MODIFY COLUMN a Int64 DEFAULT c0 + 100 SETTINGS mutations_sync = 2 fails every time on master, 26.8.18.2 and 26.3.42.3 with Code: 47 Unknown expression or function identifier c0.
b Root cause explained? The conversion that replaces NULLs with the DEFAULT is evaluated on a block holding only the converted columns, and the reader never reads the columns that DEFAULT refers to.
c Fix matches root cause? Yes. The reader reads those columns and passes the rest of the row to the conversion, as it already does for the DEFAULT of a missing column. No guard and no refusal.
d Test intent preserved / new tests added? New test 05339_modify_column_null_to_default_reads_other_column.sh: Compact and Wide parts, reads before the mutation (PREWHERE on either column, lazy materialization), a kept and a changed DEFAULT, MATERIALIZED and converted dependencies, patch parts before and after the ALTER, LowCardinality(Nullable(String)). The lazy case also asserts LazilyReadFromMergeTree in EXPLAIN.
e Both directions demonstrated? The test fails on the master binary (25 failing statements, plus a wrong 17 instead of 10) and passes on the fix. Turning off each of the four parts of the fix separately makes the cases it covers fail. 50/50 randomized runs pass.
f Fix is general across code paths? SELECT read steps, merges and mutations, patch parts written before the ALTER, projections (checked by hand). Earlier read steps are not used when a patch part or on-the-fly mutation newer than the ALTER exists, so a value written after the ALTER never reaches the DEFAULT. On-the-fly mutation steps and the patch-part reader keep today's behaviour: a loud error, never a wrong value.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable and LowCardinality(Nullable). Ordinary, MATERIALIZED and converted dependencies. The dependency read in the same step, in an earlier step, or not requested at all. A dependency the old part does not store still fails as before (stated in the description).
h Backward compatible? (maintainer-approved exception only) Yes. No setting and no format change. A table already stuck on 26.1-26.9 recovers once its mutation is retried.
i Invariants and contracts preserved? Only the converted columns are written back. The extra row columns are inputs only. A read with no NULL to DEFAULT conversion runs the same code as before.

Session id: cron:clickhouse-impl-self-slot-57:20261008-061100

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [31af886]

Summary: ✅


AI Review

Summary

The PR supplies other row columns to the DEFAULT used when converting Nullable columns to non-Nullable types. Reviewed head 31af88650b68135b138d0d9a319578bd5284521d. The basic fix has regression coverage, but the previously reported mutation-ordering defect remains reproducible and can silently persist incorrect values.

Findings

❌ Blockers

  • DEFAULT evaluation must preserve mutation order. IMergeTreeReader.cpp:931 and inplaceBlockConversions.cpp:319. [dismissed by author -- https://github.com/Fix a stuck mutation after MODIFY COLUMN from Nullable with a DEFAULT that reads another column #124561#discussion_r4506669142] The author resolved the thread without a reply; the issue remains real because ordinary mutation batching changes successfully stored results, with no cancelled mutation.

    The new inputs are source-part values, and the conversion executes before the mutation interpreter applies an earlier UPDATE. Reproduced with this head's Fast test binary:

    CREATE TABLE t (c0 Int64, a Nullable(Int64))
        ENGINE = MergeTree ORDER BY tuple();
    INSERT INTO t VALUES (1, NULL);
    SYSTEM STOP MERGES t;
    ALTER TABLE t UPDATE c0 = c0 + 10 WHERE 1
        SETTINGS mutations_sync = 0, alter_sync = 0;
    ALTER TABLE t MODIFY COLUMN a Int64 DEFAULT c0 + 100
        SETTINGS mutations_sync = 0, alter_sync = 0;
    SYSTEM START MERGES t;
    OPTIMIZE TABLE t FINAL;
    SELECT c0, a FROM t;

    This stores (11, 101) and both mutations report is_done = 1. Executing the same alterations synchronously, without stopping merges, stores (11, 111).

    The reverse dependency-conversion order also diverges: start with c0 Float64 = 1.7 and a Nullable(Int64) = NULL, first modify a to Int64 DEFAULT c0 * 10, then modify c0 to Int64. Synchronous execution stores (1, 17); batching stores (1, 10). Preferring conversion aliases unconditionally makes the earlier DEFAULT consume the later conversion's value.

    Evaluate replacement defaults at their ordered mutation boundary, after preceding changes and before subsequent ones. Reading dependencies into the source block alone does not preserve that boundary.

Tests
  • ⚠️ Add a focused regression comparing synchronous and queued execution for an UPDATE before the nullable conversion, and for a dependency type conversion after it. Assert stored values after materialization and successful mutation completion. The current test covers a dependency converted before the nullable conversion, but not these two orders.
Final Verdict

Status: ❌ Block

Preserve mutation order during NULL replacement and add the two ordering regressions. The existing author-resolved thread was left unchanged; no duplicate inline finding was posted.

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

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 31af88650 with master b915879ad (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

19 object files changed (+56.80 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/inplaceBlockConversions.cpp.o 326.46 KiB 346.53 KiB +20.07 KiB (+6.15%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/IMergeTreeReader.cpp.o 426.70 KiB 444.34 KiB +17.64 KiB (+4.14%)

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

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

Job report

alexey-milovidov and others added 3 commits October 25, 2026 11:42
…default-reads-other-columns

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The master merge brought the `MergeTreeReadersChain::previous_steps_columns`
field (`std::vector<NameSet>`), which the `Block` local of the same name in
`executeActionsBeforePrewhere` now shadows, failing `-Wshadow` in Fast test
and `Build (arm_tidy)`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…default-reads-other-columns

Resolve the conflict in `MergeTreeReadersChain::evaluateMissingDefaults`: keep
master's `mayEvaluateMissingDefaults` assertion and the shared
`getPreviousStepsColumns` helper. A reader that replaces NULLs with a DEFAULT
requests a column with a DEFAULT, so `mayEvaluateMissingDefaults` holds for it
and the earlier steps still keep the columns they project out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…default-reads-other-columns

# Conflicts:
#	src/Storages/MergeTree/MergeTreeReadersChain.cpp
#	src/Storages/MergeTree/MergeTreeReadersChain.h

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