Skip to content

Fix on-fly mutation LowCardinality pass-through column conversion - #105847

Merged
Algunenano merged 16 commits into
ClickHouse:masterfrom
Algunenano:fix-1818-on-fly-mutation-lc-conversion
Jun 10, 2026
Merged

Algunenano merged 16 commits into
ClickHouse:masterfrom
Algunenano:fix-1818-on-fly-mutation-lc-conversion

Conversation

@Algunenano

@Algunenano Algunenano commented May 26, 2026 •

Copy link
Copy Markdown
Member

Linked issues

On-fly mutations with a pending ALTER MODIFY COLUMN <c> LowCardinality(...) queued after an UPDATE/DELETE left the pass-through columns (those the mutation chain never overwrites) in their on-disk types while the block header already advertised the post-MODIFY metadata types. Downstream operators that key off the declared type then tripped on the mismatch:

  • MergingSortedTransform's ColumnLowCardinality::insertFrom → Code 44 Expected ColumnLowCardinality, got String
  • NativeWriter's typeid_cast<ColumnLowCardinality> → Code 49 LOGICAL_ERROR Bad cast from type DB::ColumnString to DB::ColumnLowCardinality
  • function execution's executeWithoutLowCardinalityColumns → SEGV on a non-LC column

AlterConversions::getMutationSteps correctly disables perform_alter_conversions for the on-fly steps (the action DAG embeds its own CAST for the columns the mutation overwrites, so pre-casting the on-disk value could fail on values the UPDATE is about to replace), but the disabling applied to every column of the step, including pass-through ones.

The fix carries the set of columns the on-fly chain actually overwrites through to PrewhereExprStep::columns_overwritten_by_chain. MergeTreeReadersChain::executeActionsBeforePrewhere then runs performRequiredConversions with those columns temporarily nulled out and restored, so pass-through columns get cast to the metadata type while the chain still sees the to-be-overwritten ones in their raw on-disk form.

The set is derived from the filtered UPDATE/DELETE chain returned by filterMutationCommands for the current read_columns. MODIFY COLUMN (READ_COLUMN) targets are not included, because those commands are not applied on-fly, they only set the fence; their columns must still go through performRequiredConversions. Commands dropped by filterMutationCommands (because the query does not need their targets) also do not contribute, so columns flowing through earlier surviving steps as pass-through reads still get converted.

cc @CurtizJ as the on-fly mutation author.

Related: #105947 (separate pre-existing bug surfaced during investigation: MODIFY COLUMN after a lightweight DELETE fails when soft-deleted rows hold unconvertible values; out of scope here.)

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 Expected ColumnLowCardinality, got String / Bad cast from type DB::ColumnString to DB::ColumnLowCardinality errors when apply_mutations_on_fly = 1 is used on a table with pending on-fly UPDATE/DELETE mutations queued before an ALTER MODIFY COLUMN ... LowCardinality(...) mutation.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.601
  • Backported to: 26.5.3.20, 26.4.5.27, 26.3.14.21

When `apply_mutations_on_fly = 1` is used with an UPDATE/DELETE mutation
queued BEFORE a pending `ALTER MODIFY COLUMN <c> LowCardinality(...)`,
`AlterConversions::getMutationSteps` sets `perform_alter_conversions =
false` on the UPDATE/DELETE step. This is correct for columns the
mutation overwrites — pre-casting them on read can fail (e.g. `CAST('x'
AS UInt64)` for a value the UPDATE is about to replace with `100`) and
the action's DAG embeds its own CAST anyway.

But the step's reader also produces pass-through columns the mutation
never touches. Skipping `performRequiredConversions` for those leaves
the block advertising the post-MODIFY metadata type (e.g.
`LowCardinality(String)`) over a bare `ColumnString`. Downstream
operators trust the declared type and trip on the mismatch
(`MergingSortedTransform`'s `ColumnLowCardinality::insertFrom` throws
`ILLEGAL_COLUMN: Expected ColumnLowCardinality, got String`;
`NativeWriter`'s `typeid_cast<ColumnLowCardinality>` throws
`LOGICAL_ERROR: Bad cast from type DB::ColumnString to
DB::ColumnLowCardinality`; function execution's
`executeWithoutLowCardinalityColumns` SEGVs on the same mismatch).

Carry the set of columns the on-fly chain will overwrite through
`PrewhereExprStep::columns_overwritten_by_chain` (populated from
`AlterConversions::all_updated_columns`). In
`MergeTreeReadersChain::executeActionsBeforePrewhere`, when a step has
`perform_alter_conversions = false`, run `performRequiredConversions`
on the read columns with the overwritten ones temporarily nulled out
and restored afterwards — so pass-through columns get cast to the
metadata type while overwritten columns still flow into the action's
DAG in their on-disk form.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Algunenano Algunenano added pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed v26.2-must-backport labels May 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e4d8874]

Summary: ✅


AI Review

Summary

This PR fixes on-fly mutation reads where pending UPDATE/DELETE steps before ALTER MODIFY COLUMN ... LowCardinality(...) left pass-through columns in their on-disk type while the block header advertised the post-MODIFY type. The current implementation derives the skip set from the filtered mutation chain, temporarily excludes only overwritten columns from performRequiredConversions, and has focused regressions for the original LowCardinality pass-through failure, the lightweight DELETE carve-out, and the filtered-chain source-column case. I did not find remaining high-signal issues in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 26, 2026
`columns_overwritten_by_chain` was set to `all_updated_columns`, which also
tracks `MODIFY COLUMN` (`READ_COLUMN`) targets. Those columns are not actually
applied on-fly — they only set the `version_of_alter_mutation` fence — so they
still need `performRequiredConversions`. Skipping conversion for them left the
column at its on-disk type while the block header advertised the post-MODIFY
type, e.g. an `ORDER BY` over a `String → LowCardinality(String)` column
threw `Code 44. Expected ColumnLowCardinality, got String` in
`MergingSortedTransform`.

Build the set from `UPDATE`/`DELETE` commands only.

Update the test to drive that exact code path: `UPDATE` queued before
`MODIFY COLUMN c LowCardinality(String)` and an `ORDER BY c` with
`query_plan_max_limit_for_lazy_materialization = 10` to keep lazy
materialization off (matching the production setting).
@ClickHouse ClickHouse deleted a comment from watson-ch Bot May 27, 2026
Lightweight DELETE queued before MODIFY COLUMN: with the narrowed
`columns_overwritten_by_chain` the MODIFY'd column still goes through
`performRequiredConversions`, so the read returns the post-MODIFY type for the
rows that survive the delete. Guards against re-broadening the set.
`MutationCommand::column_to_update_expression` was removed from the struct and
replaced by the free function `getColumnToUpdateExpression(ASTAlterCommand &)`.
Update the on-fly chain target collection to call the helper.
Documents the scenario raised by `clickhouse-gh[bot]` in PR review
discussion r3346245939: a later `UPDATE` whose target gets dropped by
`filterMutationCommands` while a `MODIFY COLUMN` is pending on the same
column. I could not reproduce a user-visible failure but locking in the
current behaviour so future changes to `AlterConversions::getMutationSteps`
or `filterMutationCommands` have to re-evaluate the case.
…sion' into fix-1818-on-fly-mutation-lc-conversion
Derive `columns_overwritten_by_chain` from the commands that actually survived
`filterMutationCommands` for the current `read_columns`, not from the full
`mutation_commands` list. A later `UPDATE` whose target is dropped because the
query does not need it was still leaving that target in the skip set, which
re-creates the type/header mismatch this PR fixes when the dropped target is
also affected by a pending `MODIFY COLUMN`.

`filterMutationCommands` converts a lightweight `UPDATE _row_exists = 0` into a
typed `DELETE` command without the original assignment, so add `_row_exists`
explicitly for any filtered `DELETE`. Plain `ALTER DELETE` is unaffected
because `_row_exists` does not need on-disk conversion.

Replace the placeholder 04308 sanity test with the reproducer suggested by
`clickhouse-gh[bot]` in PR review discussion r3350248306. Without the fix the
read throws `LOGICAL_ERROR: Unexpected return type from materialize`.
`columns_overwritten_by_chain` used to be a chain-wide union attached to every
pre-`MODIFY` step. A step that read a column as a source but did not write it
still skipped `performRequiredConversions` for that column, reintroducing the
type/header mismatch the PR sets out to fix whenever a later step in the
chain overwrites the column. `SELECT sum(b), any(a)` over
`UPDATE b = isNotNull(materialize(a))` then `UPDATE a = 'x'` then
`MODIFY a LowCardinality(Nullable(String))` reproduces the
`LOGICAL_ERROR: Unexpected return type from materialize` reported by
`clickhouse-gh[bot]` in PR review r3350564104.

Carry the overwritten set per step. `MutationsInterpreter::getMutationActions`
now populates `MutationActions::overwritten_columns` with the filter column
for a filter step or the `UPDATE` assignment targets for an expression step.
`AlterConversions::getMutationSteps` uses that per-step set when
`perform_alter_conversions` is false. The chain-wide derivation, including
the lightweight-delete `_row_exists` carve-out, is no longer needed since
the per-stage filter step already carries its filter column.

Drop the `else if (!columns_overwritten_by_chain.empty())` guard in
`MergeTreeReadersChain::executeActionsBeforePrewhere` so an empty skip set
still triggers a full conversion pass for the step.

Extend `04308_on_fly_mutation_filtered_update_chain` with a second query
(`SELECT sum(b), any(a)`) that fails without the per-step skip set.
`clickhouse-gh[bot]` (PR review r3350748853) flagged that combining the two
assignments into a single `UPDATE b = isNotNull(materialize(a)), a = 'x'` puts
`a` in the per-step skip set while the same step's expression also reads it as
a source, which could re-trigger the type/header mismatch.

I could not reproduce a user-visible failure with this shape, runtime
`materialize` handles `a` arriving as the on-disk `Nullable(String)` even when
the action DAG was analysed against `LowCardinality(Nullable(String))`. Locking
the scenario into `04308_on_fly_mutation_filtered_update_chain` as a sanity
check so any future change to action analysis or to the per-step skip set has
to re-evaluate it.
`clickhouse-gh[bot]` (PR review r3350836226) suggested `isNull(a)` as a stricter
function-dispatch path than the variant-3 `isNotNull(materialize(a))`. Same
single-stage shape: `UPDATE b = isNull(a), a = 'x'` followed by
`MODIFY COLUMN a LowCardinality(Nullable(String))`.

Still no user-visible failure under the per-step skip set. Runtime function
dispatch checks the actual column class rather than the DAG-declared type, so
`a` arriving as `ColumnNullable` does not enter the `isLowCardinalityNullable`
branch. Locked in as variant 4 of `04308_on_fly_mutation_filtered_update_chain`.
`columns_overwritten_by_chain` was built from the full `mutation_commands`
list. A later `UPDATE` whose target the query did not need was still
contributing to the skip set, so an earlier surviving step that reads that
column as a source saw the on-disk type while the block already advertised
the post-`MODIFY` type. Build the set from the chain that
`filterMutationCommands` returns for the current `read_columns` so dropped
commands no longer contribute.

`filterMutationCommands` rewrites a lightweight `UPDATE _row_exists = 0`
into a `DELETE` typed command without the original assignment. Add
`_row_exists` explicitly for any filtered `DELETE` so the lightweight delete
chain still skips it from conversion.

Trim `04308_on_fly_mutation_filtered_update_chain` to cover the filtered
chain case; the per-step variants depend on a deeper change in mutation
action analysis and are left to a follow-up.

Also drop the per-stage / per-path branching in
`MutationsInterpreter::getMutationActions` by collecting both analyser paths
into a single vector of `ActionsAndProjectInputsFlagPtr`.
@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai if you would take tests from this branch, can you come up a smaller diff for the fix?

@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator

@nikitamikhaylov ack. Two reducible parts in the current diff (965647d3):

  1. The MutationsInterpreter::getMutationActions consolidation (+16 -28) is a code-quality cleanup, not part of the fix. Dropping it leaves master untouched and saves ~30 lines.

  2. columns_overwritten_by_chain is recomputed in AlterConversions::getMutationSteps by re-running filterMutationCommands and getColumnToUpdateExpression on each command. The same info is already present in the actions_chain returned right above: each MutationActions::dag carries the step's outputs (= columns it writes). The chain-wide union is union(dag.getOutputs()) over all steps, plus _row_exists when a typed DELETE is in the chain. ~25 fewer lines in AlterConversions.cpp.

Irreducible mechanism: the NameSet field on PrewhereExprStep (5 init sites) and the per-column null-and-restore in MergeTreeReadersChain::executeActionsBeforePrewhere. The skip set has to reach the conversion call, and IMergeTreeReader::performRequiredConversions already short-circuits on nullptr, so null-and-restore is the cheapest mechanism.

Further reduction would mean per-step skip, but that path is closed: UPDATE v = '100' lists v as a structural input of the step's DAG even though the literal assignment doesn't consume it, so any per-step skip that subtracts source inputs runs _CAST('x', UInt64) over on-disk 'x' and breaks 03047_on_fly_mutations_alters. The chain-wide skip is what survives that test.

Happy to push the two reductions as a follow-up commit on a draft branch if you want to see the patch.

@Algunenano

Copy link
Copy Markdown
Member Author

@groeneai Apparently nobody wants to review this critical PR. Can you do it please?

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed at HEAD 965647d3aabc5927d8dcc9ba8aa542810cbc366a. CI is green (143 SUCCESS, 19 SKIPPED, 0 FAILURE), so this is a correctness/scope review. The bot's prior thread (chain-wide vs per-step skip set, filtered chain, materialize same-stage shape) has already been resolved; my comments below are scoped to what is left.

Verdict

Approve in principle. The chain-wide null-and-restore around performRequiredConversions is the right shape: per-step skipping is closed by 03047_on_fly_mutations_alters (an action DAG can list a column as a structural-but-dead input), the deeper "build the on-fly DAG against the part's on-disk schema" refactor is genuinely out of scope, and the new tests (04267, 04268, 04308) lock in all three sub-shapes in the right direction. Minor reduction and a few small clarifications below.

Diff reduction (per @ nikitamikhaylov)

Two reducible parts in the current diff. Together they save roughly 50 lines without changing behaviour:

  1. The MutationsInterpreter::getMutationActions consolidation (+16 -28) is a code-quality cleanup, not part of the fix. It can be split out (or dropped) and the rest of the PR stands on its own. Master is otherwise untouched.

  2. In AlterConversions::getMutationSteps, columns_overwritten_by_chain is recomputed by replaying filterMutationCommands + getColumnToUpdateExpression. The same information is already in actions_chain: each MutationActions::dag exposes its outputs via dag.getOutputs(). A union of those outputs (plus RowExistsColumn::name whenever the chain contains a typed DELETE) gives the same set without the second pass. Roughly:

    NameSet columns_overwritten_by_chain;
    for (const auto & actions : actions_chain)
    {
        for (const auto * out : actions.dag.getOutputs())
            columns_overwritten_by_chain.insert(out->result_name);
        if (!actions.filter_column_name.empty())  // typed DELETE step
            columns_overwritten_by_chain.insert(RowExistsColumn::name);
    }

    I have not pushed this against your branch (it is yours to land). Happy to send it as a follow-up commit if it is useful.

Minor issues

1. Comment vs. code mismatch on RowExistsColumn::name insertion

AlterConversions.cpp:348-355. The comment reads:

Lightweight delete arrives as a DELETE typed command without the original _row_exists = 0 assignment; add it explicitly so the chain skips it from conversion. Plain ALTER DELETE is unaffected (_row_exists is virtual).

The code unconditionally inserts _row_exists for any command.type == DELETE. filterMutationCommands returns a DELETE-typed command in two situations:

  • The original ALTER DELETE (type DELETE from the start).
  • A lightweight delete that was rewritten by createLightweightDeleteCommand (line 567) into a DELETE-typed command.

Both end up inserting _row_exists here. For plain ALTER DELETE it is harmless (no on-disk _row_exists, so nothing for performRequiredConversions to skip), but the comment implies plain ALTER DELETE does not contribute. Either tighten the condition (only insert when this command was synthesised by createLightweightDeleteCommand, e.g. by tracking that intent), or update the comment to read "added unconditionally for any chained DELETE; harmless for plain ALTER DELETE because _row_exists is virtual and there is no on-disk column to convert".

2. Subcolumn assignment targets

The skip set is built from getColumnToUpdateExpression, which returns the assignment target names verbatim. If a user wrote ALTER UPDATE n.x = ... (rare, but possible), the set would carry n.x. The MergeTreeReadersChain::executeActionsBeforePrewhere lookup keys on name_and_type.getNameInStorage(), which returns the parent storage name (n) for a subcolumn read. The skip would not match.

In practice ClickHouse does not really support per-subcolumn updates of Nested arrays, so this is theoretical. Worth a short comment in AlterConversions::getMutationSteps noting that the set is expected to contain top-level storage names; if a subcolumn assignment ever becomes supported, the skip key on the reader side would need to change to handle it.

3. Test tag and minor robustness

  • 04267_on_fly_mutation_lc_passthrough_conversion.sql, 04268_on_fly_mutation_delete_modify_chain.sql, 04308_on_fly_mutation_filtered_update_chain.sql: all three use MergeTree + SYSTEM STOP MERGES + manual mutation queueing. They look fine; just confirm they have not picked up no-shared-merge-tree accidentally elsewhere. The existing 03047_on_fly_mutations_alters.sh carries that tag because it uses ReplicatedMergeTree('/clickhouse/tables/...').
  • The enable_block_number_column = 1, enable_block_offset_column = 1 settings on 04268 look unused by the assertions. Drop them unless they are deliberately exercising on-fly behaviour with those columns present.

Risk areas already covered (for reviewer reference)

  • Chain-wide vs per-step skip set. The bot's "narrower per-step set" suggestion is closed by 03047_on_fly_mutations_alters (UPDATE v = '100' WHERE 1). The new 04308 is the regression test pinning the chain-wide direction; confirmed it fails on naive per-step.
  • Filtered chain vs all mutation_commands. Already addressed by 965647d3 (the bot's 04308 shape and your reproduction). Skip set is now built from filterMutationCommands results.
  • MutationsInterpreter::performRequiredConversions null skip. Confirmed at IMergeTreeReader.cpp:413 (if (res_columns[pos] == nullptr) continue;). The null-and-restore approach is sound.
  • Same-stage UPDATE b = isNotNull(materialize(a)), a = 'x'. The bot's two same-stage shapes do not reproduce on this PR; the pre-existing materialize LOGICAL_ERROR also fires on master pre-PR (tracked in #105947).
  • Soft-deleted DELETE + MODIFY + unconvertible values. Out of scope; tracked in #105947 (your investigation issue).

Out of scope / followups

  • #105947 covers the cast-before-filter and on-disk-DAG-build fixes that would make this whole class robust. PR #105847 is the right narrow first step.
  • #101874 (lightweight delete mutation_version propagation) is the masked sibling bug in the same area.

Revert the `MutationsInterpreter::getMutationActions` consolidation. The change
was cosmetic, not part of the fix, and shrinks the backport surface to keep
only the chain-wide skip set in `AlterConversions`.

Clarify the comment on the `RowExistsColumn::name` insertion: it fires for any
chained `DELETE`, lightweight or plain. Plain `ALTER DELETE` does not have an
on-disk `_row_exists` column, so the explicit insert is harmless for
`performRequiredConversions`.

Add a note that the skip is keyed on storage column names. Assignment targets
are top-level columns today; per-subcolumn `Nested` assignments would need a
matching change on the reader-side key.

Drop the `enable_block_number_column = 1, enable_block_offset_column = 1` clause
from `04268_on_fly_mutation_delete_modify_chain`. Verified the bug reproduces
identically with the settings on and off, and `clickhouse-test` randomises both.

The `dag.getOutputs()` simplification from the review does not work: each
step's outputs list every column the step produces, including pass-through
sources, so the skip set would over-skip and bring back the original
LowCardinality pass-through mismatch.
robot-clickhouse-ci-1 added a commit that referenced this pull request Jun 10, 2026
Cherry pick #105847 to 26.4: Fix on-fly mutation LowCardinality pass-through column conversion
robot-clickhouse added a commit that referenced this pull request Jun 10, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Jun 10, 2026
Cherry pick #105847 to 26.5: Fix on-fly mutation LowCardinality pass-through column conversion
robot-clickhouse added a commit that referenced this pull request Jun 10, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 10, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 10, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 10, 2026
Algunenano added a commit that referenced this pull request Jun 11, 2026
Backport #105847 to 26.3: Fix on-fly mutation LowCardinality pass-through column conversion
Algunenano added a commit that referenced this pull request Jun 11, 2026
Backport #105847 to 26.4: Fix on-fly mutation LowCardinality pass-through column conversion
Algunenano added a commit that referenced this pull request Jun 11, 2026
Backport #105847 to 26.5: Fix on-fly mutation LowCardinality pass-through column conversion
@watson-ch watson-ch Bot added v26.2-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Jun 12, 2026
@watson-ch

watson-ch Bot commented Jun 12, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/1818

Labels added:

  • v26.2-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@watson-ch

watson-ch Bot commented Jun 12, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/1846

Labels added:

  • v25.12-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 12, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 12, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 15, 2026
…tten LowCardinality source column

On-fly mutation prewhere steps that precede a pending ALTER MODIFY COLUMN are
read with perform_alter_conversions = false, and every column the chain
overwrites is exempted from performRequiredConversions: its on-disk value is
about to be discarded by the UPDATE's own CAST, and pre-casting it could fail
on a value being replaced (e.g. CAST('x' AS UInt64) before UPDATE v = '100').

The conversion of a column happens once, in the reader that first reads it from
disk. But the column may be consumed as a function input by a LATER on-fly
mutation step in the chain. Consider:

  UPDATE b = isNotNull(materialize(a));
  UPDATE a = 'x';
  MODIFY COLUMN a LowCardinality(Nullable(String));

A query that reads both b and a (e.g. SELECT sum(b), any(a)) keeps the
UPDATE a command, so a lands in the overwritten set and its conversion is
skipped. The UPDATE b step's action, built against the post-MODIFY metadata,
then runs materialize(a) expecting LowCardinality(Nullable(String)) but receives
an on-disk Nullable(String), aborting with
LOGICAL_ERROR: Unexpected return type from materialize. The fix in ClickHouse#105847 only
covered the case where reading just b drops the UPDATE a; the per-step variants
were left to a follow-up.

Compute, once per reader chain, the set of columns consumed as a FUNCTION /
ARRAY_JOIN input by an on-fly MUTATION step's action DAG (walking ALIAS chains
back to the INPUT node), and keep those columns out of the conversion skip set.
The scan is restricted to mutation steps (perform_alter_conversions == false).
A mutation step's action DAG is always built against the post-MODIFY metadata
type, so any column it reads must arrive converted. Trailing query PREWHERE and
row-level-filter steps (perform_alter_conversions == true) are excluded: they
run after the whole mutation chain has produced the final, correctly typed
column and convert at their own turn. Counting their consumption would force a
premature conversion of an about-to-be-discarded on-disk value, e.g.
PREWHERE v > 50 casting on-disk 'x' to UInt64 before UPDATE v = '100' replaces
it (CANNOT_PARSE_TEXT). A column that is only overwritten and never read by a
mutation action (e.g. v in UPDATE v = '100') still skips conversion, so the
original case the skip was added for is preserved.

The regression test covers both: the materialize(a) over LowCardinality case,
and the overwrite-then-query-PREWHERE case that an earlier chain-wide scan
regressed.

Found by the server-side AST fuzzer (serverfuzz) on master.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 15, 2026
…tten LowCardinality source column

On-fly mutation prewhere steps that precede a pending ALTER MODIFY COLUMN are
read with perform_alter_conversions = false, and every column the chain
overwrites is exempted from performRequiredConversions: its on-disk value is
about to be discarded by the UPDATE's own CAST, and pre-casting it could fail
on a value being replaced (e.g. CAST('x' AS UInt64) before UPDATE v = '100').

The conversion of a column happens once, in the reader that first reads it from
disk. But the column may be consumed as a function input by a LATER on-fly
mutation step in the chain. Consider:

  UPDATE b = isNotNull(materialize(a));
  UPDATE a = 'x';
  MODIFY COLUMN a LowCardinality(Nullable(String));

A query that reads both b and a (e.g. SELECT sum(b), any(a)) keeps the
UPDATE a command, so a lands in the overwritten set and its conversion is
skipped. The UPDATE b step's action, built against the post-MODIFY metadata,
then runs materialize(a) expecting LowCardinality(Nullable(String)) but receives
an on-disk Nullable(String), aborting with
LOGICAL_ERROR: Unexpected return type from materialize. The fix in ClickHouse#105847 only
covered the case where reading just b drops the UPDATE a; the per-step variants
were left to a follow-up.

Compute, once per reader chain, the set of columns consumed as a FUNCTION input
by an on-fly MUTATION step's action DAG, and keep those columns out of the
conversion skip set. The scan is restricted to mutation steps
(perform_alter_conversions == false). A mutation step's action DAG is always
built against the post-MODIFY metadata type, so any column it reads must arrive
converted. Trailing query PREWHERE and row-level-filter steps
(perform_alter_conversions == true) are excluded: they run after the whole
mutation chain has produced the final, correctly typed column and convert at
their own turn. Counting their consumption would force a premature conversion
of an about-to-be-discarded on-disk value, e.g. PREWHERE v > 50 casting on-disk
'x' to UInt64 before UPDATE v = '100' replaces it (CANNOT_PARSE_TEXT). A column
that is only overwritten and never read by a mutation action (e.g. v in
UPDATE v = '100') still skips conversion, so the original case the skip was
added for is preserved.

A mutation step's action DAG binds a function argument directly to its source
node (INPUT, FUNCTION, or COLUMN); ALIAS nodes appear only as a step's named
output, never as a function argument. arrayJoin is rejected for mutations in
MutationsInterpreter because it changes the row count, so an ARRAY_JOIN node
never reaches a mutation step's DAG. The scan therefore collects INPUT
arguments directly and asserts both invariants, rather than walking ALIAS
chains or handling ARRAY_JOIN that cannot occur.

The regression test covers both: the materialize(a) over LowCardinality case,
and the overwrite-then-query-PREWHERE case that an earlier chain-wide scan
regressed.

Found by the server-side AST fuzzer (serverfuzz) on master.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…5847

Backport ClickHouse#105847 to 26.4: Fix on-fly mutation LowCardinality pass-through column conversion
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
STOR: apply_mutations_on_fly=1 with UPDATE/DELETE queued before MODIFY COLUMN to LowCardinality -> exc (Bad cast).
Effect in the production build a394e92: its upstream test(s) 04267_on_fly_mutation_lc_passthrough_conversion, 04268_on_fly_mutation_delete_modify_chain, 04308_on_fly_mutation_filtered_update_chain fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04267_on_fly_mutation_lc_passthrough_conversion,04268_on_fly_mutation_delete_modify_chain,04308_on_fly_mutation_filtered_update_chain.

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

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v25.12-must-backport v26.2-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants