Skip to content

Fix Nullable(X)->Y cross-type ALTER MODIFY COLUMN - #102156

Merged
Michicosun merged 10 commits into
ClickHouse:masterfrom
il9ue:fix/nullable-cross-type-modify-upstream
Jul 24, 2026
Merged

Michicosun merged 10 commits into
ClickHouse:masterfrom
il9ue:fix/nullable-cross-type-modify-upstream

Conversation

@il9ue

@il9ue il9ue commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category

  • Bug Fix

Changelog entry

Fixed ALTER MODIFY COLUMN failing when converting a Nullable column to a different type with a DEFAULT (e.g. Nullable(UInt8) → String,LowCardinality(String), or Array(UInt8)).

Details

Follow-up to #84770. convertRequiredExpressions now branches on whether the target type can be nested in Nullable:

  • Nullable-able targets (String, LowCardinality, numerics): ifNull(_CAST(col, 'Nullable(T)'), _CAST(default, 'T')) — NULLs pass through the cast unparsed, so this path is exception-safe regardless of settings.
  • Targets that cannot be inside Nullable (Array/Tuple/Map): no valid Nullable(T) exists, so it branches per row: if(isNull(col), _CAST(default, 'T'), _CAST(assumeNotNull(col), 'T')).

Behavior note: the second form relies on short-circuit evaluation. On a NULL row assumeNotNull(col) exposes the placeholder (e.g. '') and _CAST of it can throw; with short_circuit_function_evaluation enabled (the default) the value branch is skipped for NULL rows. The test pins this and tags no-random-settings.

The masking by use_variant_as_common_type (#96790) is why the regression test sets it to 0 to reproduce on master.

@alesapin alesapin self-assigned this Apr 9, 2026
@alesapin alesapin added the can be tested Allows running workflows for external contributors label Apr 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3fe6a7d]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, parallel) FAIL
03356_analyzer_unused_scalar_subquery FAIL cidb
Integration tests (amd_msan, 7/8) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue

AI Review

Summary

This PR rewrites the Nullable(X) -> Y ALTER MODIFY COLUMN conversion path to use a single generated if expression plus an outer _CAST, and it adds broad stateless coverage for cross-type conversions. I’m requesting changes because the new generic expression still depends on short_circuit_function_evaluation for complex non-nullable targets, so the bug fix is incomplete.

Findings

❌ Blockers

  • [src/Interpreters/inplaceBlockConversions.cpp:186-191] The generated _CAST(if(isNull(col), _CAST(default, 'T'), _CAST(assumeNotNull(col), 'T')), 'T') still violates the PR contract for non-Nullable-able targets when short_circuit_function_evaluation = 'disable'. ExpressionActions disables lazy if evaluation in that mode, assumeNotNull returns the nested placeholder for NULL rows, and CAST from String to Array / Tuple / Map parses via deserializeWholeText, which rejects '' because it does not start with [ / ( / {. A concrete trace is Nullable(String) -> Array(UInt8) DEFAULT []: the NULL row still evaluates _CAST(assumeNotNull(x), 'Array(UInt8)') on '' before if can select the default branch, so valid ALTER conversions and reads of old parts can still raise an exception under that supported setting.
    Suggested fix: make this internal conversion independent of user short-circuit settings, for example by restoring the nullable-cast path for targets that can be wrapped in Nullable and forcing short-circuit evaluation only for the fallback branch, or by using another eager-safe construction. The regression should execute a shape whose NULL placeholder is not castable to the target under short_circuit_function_evaluation = 'disable', such as Nullable(String) -> Array(UInt8) / Tuple(UInt8, UInt8) / Map(String, UInt8).
Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 9, 2026
@il9ue

il9ue commented Apr 11, 2026

Copy link
Copy Markdown
Contributor Author

Remarks on CI Failures

All CI failures are pre-existing timeouts on ARM ASAN/UBSAN builds (sanitizer overhead causes 300s/10min query timeouts) and a known BuzzHouse DDL worker assertion. None involve nullable conversion or files touched by this PR. Our test (03575_modify_column_null_to_default_cross_type) passed across all configurations.

@alesapin

Copy link
Copy Markdown
Member

@il9ue, the issues is that the test 03575_modify_column_null_to_default_cross_type pass on master branch as well, without your fix. See bugfix validation check, the idea of this check is to run freshly added tests on master. If they don't fail than test doesn't reproduce the bug.

@il9ue

il9ue commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Valid point, thanks!
The test passes on master because use_variant_as_common_type defaults to true in v26.x, which makes ifNull resolve via Variant types (#96790) and masks the bug.

I will update the test to set use_variant_as_common_type = 0, which reproduces the underlying issue in convertRequiredExpressions() even on master. This would also demonstrate why the fix matters for older branches (24.8, 25.8) where Variant support isn't the default.

@il9ue, the issues is that the test 03575_modify_column_null_to_default_cross_type pass on master branch as well, without your fix. See bugfix validation check, the idea of this check is to run freshly added tests on master. If they don't fail than test doesn't reproduce the bug.

PR ClickHouse#84770 generates _CAST(ifNull(col, default), TargetType).
When source and target base types differ (e.g. Nullable(UInt8) -> String),
ifNull throws NO_COMMON_TYPE because getLeastSupertype({UInt8, String}) fails.

Fix: swap to ifNull(_CAST(col, Nullable(TargetType)), _CAST(default, TargetType)).
This works independently of use_variant_as_common_type and handles
both same-type and cross-type nullable conversions correctly.

Signed-off-by: Daniel Q <[email protected]>
@il9ue
il9ue force-pushed the fix/nullable-cross-type-modify-upstream branch from d11480a to 4f7386c Compare April 22, 2026 06:25
@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Dear @alesapin, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot Jun 4, 2026
@Michicosun Michicosun self-assigned this Jun 4, 2026
…OLUMN

Address review on ClickHouse#102156.

The previous fix built the intermediate cast target by string-concatenating
"Nullable(" + type->getName() + ")". For a LowCardinality(T) target this
produced Nullable(LowCardinality(T)), which is invalid (LowCardinality cannot
be nested inside Nullable), so _CAST threw before ifNull could replace NULLs.

Use makeNullableOrLowCardinalityNullable(required_column.type)->getName()
instead, which yields LowCardinality(Nullable(T)) for LowCardinality targets
and Nullable(T) otherwise, and is a no-op for already-nullable targets. The
constructed expression is now ifNull(_CAST(col, 'Nullable(T)'),
_CAST(default, 'T')), documented inline in place of the prose comment.

Extend the stateless test with a Nullable(UInt8) -> LowCardinality(String)
case, and set use_variant_as_common_type = 0 so it reproduces the
NO_COMMON_TYPE failure on master (otherwise Variant resolution via ClickHouse#96790
masks the bug and bugfix-validation passes without the fix).
@CLAassistant

CLAassistant commented Jun 8, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
3 out of 4 committers have signed the CLA.

✅ alexey-milovidov
✅ il9ue
✅ Michicosun
❌ Daniel Q. Kim


Daniel Q. Kim seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@il9ue
il9ue requested a review from Michicosun June 17, 2026 05:45
auto cast_value = makeASTFunction("_CAST",
makeASTFunction("assumeNotNull", make_intrusive<ASTIdentifier>(required_column.name)),
make_intrusive<ASTLiteral>(required_column.type->getName()));
convert_func = makeASTFunction("if", std::move(is_null), std::move(cast_default), std::move(cast_value));

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.

This still makes valid Nullable(X) -> non-Nullable-able target conversions depend on the caller's short_circuit_function_evaluation setting. performRequiredConversions builds ExpressionActions from the query/read context, and when the setting is disable the third argument is evaluated before if, so a NULL row in the new test shape executes _CAST(assumeNotNull(x), 'Array(UInt8)') on the nested placeholder ('') and throws before the default branch can be selected.

That means SET short_circuit_function_evaluation = 'disable'; ALTER TABLE ... MODIFY COLUMN x Array(UInt8) DEFAULT [] still fails, and reads of old parts with a pending MODIFY COLUMN can fail the same way until the mutation materializes. Please make this internal conversion independent of the user setting, for example by forcing lazy execution for this generated expression or by using an eager-safe expression, and add a regression with short_circuit_function_evaluation = 'disable'.

@il9ue
il9ue force-pushed the fix/nullable-cross-type-modify-upstream branch from 8b216a7 to 14278f5 Compare June 18, 2026 11:19
@il9ue
il9ue force-pushed the fix/nullable-cross-type-modify-upstream branch from 14278f5 to 76fab57 Compare June 18, 2026 13:38
…column type

Follow-up to ClickHouse#84770 / the LowCardinality revision. convertRequiredExpressions
builds the null-filling conversion and now pins the result to exactly
required_column.type on both branches:

  - Nullable-able targets (String, LowCardinality, numerics):
      _CAST(ifNull(_CAST(col, 'LowCardinality(Nullable(T))'), _CAST(default, 'T')), 'T')
    The inner ifNull already resolves to the non-nullable target because the
    default arg is non-nullable; the outer _CAST pins the type explicitly so the
    generated column does not depend on ifNull's supertype resolution, and keeps
    this branch symmetric with the Array branch below.

  - Targets that cannot be nested in Nullable (Array/Tuple/Map/...):
      _CAST(ifNull(col, _CAST(default, 'X')), 'T')   (X = source base type)
    NULL rows are replaced by the default re-encoded in the source type before any
    cast to T, so the placeholder is never parsed; no branch to short-circuit, so
    independent of short_circuit_function_evaluation.

Test 03575 covers scalar String, LowCardinality(String), and Array(UInt8) targets,
each with a NULL source row taking the DEFAULT, materialized with OPTIMIZE TABLE
... FINAL to exercise the part-writer path, plus an Array case under
short_circuit_function_evaluation = 'disable'. Reproduces on upstream/master with
NO_COMMON_TYPE when use_variant_as_common_type = 0.

Signed-off-by: Daniel Q <[email protected]>
@il9ue
il9ue force-pushed the fix/nullable-cross-type-modify-upstream branch from 76fab57 to 7d10fe4 Compare June 26, 2026 11:20
…ple/Map)

Follow-up to ClickHouse#84770 / the LowCardinality revision. `convertRequiredExpressions`
builds the null-filling conversion and pins the result to exactly
`required_column.type` on both branches:

  - Nullable-able targets (`String`, `LowCardinality`, numerics):
      `_CAST(ifNull(_CAST(col, 'LowCardinality(Nullable(T))'), _CAST(default, 'T')), 'T')`
    The inner `ifNull` already resolves to the non-nullable target because its
    default arg is non-nullable; the outer `_CAST` pins the type explicitly so the
    generated column does not depend on `ifNull`'s supertype resolution, and keeps
    this branch symmetric with the else branch below.

  - Targets that cannot be nested in `Nullable` (`Array`/`Tuple`/`Map`/...):
      `if(isNull(col), _CAST(default, 'T'), _CAST(assumeNotNull(col), 'T'))`
    The default now stays on the TARGET side. The previous construction re-encoded
    the default in the source base type,
    `_CAST(ifNull(col, _CAST(default, 'X')), 'T')` (X = source base type), which
    threw `TYPE_MISMATCH` whenever the target default is not castable back to the
    source type. For example, a `Map` target with a `map(...)` default over a
    `Nullable(Tuple(...))` source built `_CAST(map('a', 1), 'Tuple(...)')`, and
    `CAST AS Tuple` rejects `Map` input. Keeping the default in the target type
    avoids the source round-trip entirely.

    The value branch `_CAST(assumeNotNull(col), 'T')` would throw on NULL rows if
    it parsed the `assumeNotNull` placeholder, but `performRequiredConversions`
    runs the expression through `ExpressionActions` that lazily evaluate
    short-circuit functions regardless of `short_circuit_function_evaluation`, so
    the branch is only evaluated for non-NULL rows. Measured: a plain top-level
    `if` over the same placeholder throws under
    `short_circuit_function_evaluation = 'disable'`, while this conversion path
    does not.

Test 03575 covers scalar `String`, `LowCardinality(String)`, `Array(UInt8)`,
`Tuple`, and `Map` targets, each with a NULL source row taking the `DEFAULT`,
materialized with `OPTIMIZE TABLE ... FINAL` to exercise the part-writer path,
plus an `Array` case under `short_circuit_function_evaluation = 'disable'`. The
scalar cases reproduce on upstream/master with `NO_COMMON_TYPE` when
`use_variant_as_common_type = 0`; the new `Map`-over-`Tuple` regression (Case 9)
reproduces with `TYPE_MISMATCH` on the previous source-round-trip else branch.

Signed-off-by: Daniel Q <[email protected]>
@il9ue

il9ue commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

regression check

The arm_tsan stress hung-check failure is unrelated to this PR.
The stack traces are all AST-fuzzer queries (pointInEllipses, catboostEvaluate, arrayReduce with bad arg counts), and none touching convertRequiredExpressions / MODIFY COLUMN / this test.
Looks like a pre-existing flake, FYI

Comment on lines +208 to +217
/// if(isNull(col), _CAST(default, 'T'), _CAST(assumeNotNull(col), 'T'))
/// Default stays target-side (no source round-trip). Value branch runs only on
/// non-NULL rows: this conversion path evaluates short-circuit funcs lazily.
auto is_null = makeASTFunction("isNull", make_intrusive<ASTIdentifier>(required_column.name));
auto cast_default = makeASTFunction("_CAST", default_value,
make_intrusive<ASTLiteral>(required_column.type->getName()));
auto cast_value = makeASTFunction("_CAST",
makeASTFunction("assumeNotNull", make_intrusive<ASTIdentifier>(required_column.name)),
make_intrusive<ASTLiteral>(required_column.type->getName()));
convert_func = makeASTFunction("if", std::move(is_null), std::move(cast_default), std::move(cast_value));

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.

I suppose we can leave only this branch, as it is generic?

@il9ue il9ue Jul 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Double-checked at the local with the testcase 2, because that one represents the case above. Removing the if-branch and running Nullable(UInt8) -> LowCardinality(String) DEFAULT 'def',

./build/programs/clickhouse local --query "
SET use_variant_as_common_type = 0;
CREATE TABLE lc (x Nullable(UInt8), y String) ENGINE=MergeTree ORDER BY tuple();
INSERT INTO lc VALUES (NULL,'a'),(7,'b');
ALTER TABLE lc MODIFY COLUMN x LowCardinality(String) DEFAULT 'def';
OPTIMIZE TABLE lc FINAL;
SELECT toTypeName(x), x, y FROM lc ORDER BY y;
"

and had a exception as below,

Code: 341. DB::Exception: Exception happened during execution of mutation 'mutation_2.txt' with part 'all_1_1_0' reason: 'Code: 49. DB::Exception: Bad cast from type DB::ColumnString to DB::ColumnLowCardinality. (LOGICAL_ERROR) (version 26.7.1.1)'. This error maybe retryable or not. In case of unretryable error, mutation can be killed with KILL MUTATION query

As far as I understood, the generic if(...) builds a plain ColumnString and just re-labels it LowCardinality(String), and it never builds the dictionary column. So at part-write the mutation fails casting ColumnString into ColumnLowCardinality.

The if-branch's _CAST(col, 'LowCardinality(Nullable(T))') is what actually builds the dictionary, so the branches aren't redundant for LowCardinality.

@Michicosun Please correct me if I'm mistaken!

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.

I think this will work

/// _CAST(if(isNull(col), _CAST(default, 'T'), _CAST(assumeNotNull(col), 'T')), 'T')
auto is_null = makeASTFunction("isNull", make_intrusive<ASTIdentifier>(required_column.name));
auto cast_default = makeASTFunction("_CAST", default_value, make_intrusive<ASTLiteral>(required_column.type->getName()));
auto cast_value = makeASTFunction("_CAST", makeASTFunction("assumeNotNull", make_intrusive<ASTIdentifier>(required_column.name)), make_intrusive<ASTLiteral>(required_column.type->getName()));
auto filled = makeASTFunction("if", std::move(is_null), std::move(cast_default), std::move(cast_value));
auto convert_func = makeASTFunction("_CAST", std::move(filled), make_intrusive<ASTLiteral>(required_column.type->getName()));
conversion_expr_list->children.emplace_back(setAlias(convert_func, required_column.name));

@Michicosun
Michicosun enabled auto-merge July 23, 2026 10:38
@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

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

Full report · Diff report

@Michicosun
Michicosun added this pull request to the merge queue Jul 24, 2026
Merged via the queue into ClickHouse:master with commit cceaa01 Jul 24, 2026
176 of 179 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 Jul 24, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…OLUMN

Address review on ClickHouse#102156.

The previous fix built the intermediate cast target by string-concatenating
"Nullable(" + type->getName() + ")". For a LowCardinality(T) target this
produced Nullable(LowCardinality(T)), which is invalid (LowCardinality cannot
be nested inside Nullable), so _CAST threw before ifNull could replace NULLs.

Use makeNullableOrLowCardinalityNullable(required_column.type)->getName()
instead, which yields LowCardinality(Nullable(T)) for LowCardinality targets
and Nullable(T) otherwise, and is a no-op for already-nullable targets. The
constructed expression is now ifNull(_CAST(col, 'Nullable(T)'),
_CAST(default, 'T')), documented inline in place of the prose comment.

Extend the stateless test with a Nullable(UInt8) -> LowCardinality(String)
case, and set use_variant_as_common_type = 0 so it reproduces the
NO_COMMON_TYPE failure on master (otherwise Variant resolution via ClickHouse#96790
masks the bug and bugfix-validation passes without the fix).
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…pe-modify-upstream

Fix Nullable(X)->Y cross-type ALTER MODIFY COLUMN
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Oct 27, 2026
24.8.14 Backport of ClickHouse#102156: Fix Nullable(X)->Y cross-type ALTER MODIFY COLUMN
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Oct 27, 2026
Antalya 25.8 Backport of ClickHouse#102156 - Fix Nullable(X)->Y cross-type ALTER MODIFY COLUMN
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Oct 28, 2026
Stable 25.8 Backport of ClickHouse#102156 - Fix Nullable(X)->Y cross-type ALTER MODIFY COLUMN
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Oct 28, 2026
Stable 26.3 Backport of ClickHouse#102156 - Fix Nullable(X)->Y cross-type ALTER MODIFY COLUMN
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Oct 28, 2026
Antalya 26.6 Backport of ClickHouse#102156 - Fix Nullable(X)->Y cross-type ALTER MODIFY COLUMN
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Oct 29, 2026
Antalya 26.3 Backport of ClickHouse#102156 - Fix Nullable(X)->Y cross-type ALTER MODIFY COLUMN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants