Repository navigation
Fix on-fly mutation LowCardinality pass-through column conversion - #105847
Algunenano merged 16 commits into
Conversation
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]>
|
Workflow [PR], commit [e4d8874] Summary: ✅
AI ReviewSummaryThis PR fixes on-fly mutation reads where pending Final VerdictStatus: ✅ Approve |
`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).
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.
…tation-lc-conversion
`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`.
|
@groeneai if you would take tests from this branch, can you come up a smaller diff for the fix? |
|
@nikitamikhaylov ack. Two reducible parts in the current diff (
Irreducible mechanism: the Further reduction would mean per-step skip, but that path is closed: Happy to push the two reductions as a follow-up commit on a draft branch if you want to see the patch. |
|
@groeneai Apparently nobody wants to review this critical PR. Can you do it please? |
groeneai
left a comment
There was a problem hiding this comment.
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:
-
The
MutationsInterpreter::getMutationActionsconsolidation (+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. -
In
AlterConversions::getMutationSteps,columns_overwritten_by_chainis recomputed by replayingfilterMutationCommands+getColumnToUpdateExpression. The same information is already inactions_chain: eachMutationActions::dagexposes its outputs viadag.getOutputs(). A union of those outputs (plusRowExistsColumn::namewhenever the chain contains a typedDELETE) 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
DELETEtyped command without the original_row_exists = 0assignment; add it explicitly so the chain skips it from conversion. PlainALTER DELETEis unaffected (_row_existsis 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(typeDELETEfrom the start). - A lightweight delete that was rewritten by
createLightweightDeleteCommand(line 567) into aDELETE-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 useMergeTree+SYSTEM STOP MERGES+ manual mutation queueing. They look fine; just confirm they have not picked upno-shared-merge-treeaccidentally elsewhere. The existing03047_on_fly_mutations_alters.shcarries that tag because it usesReplicatedMergeTree('/clickhouse/tables/...').- The
enable_block_number_column = 1, enable_block_offset_column = 1settings on04268look 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 new04308is the regression test pinning the chain-wide direction; confirmed it fails on naive per-step. - Filtered chain vs all
mutation_commands. Already addressed by965647d3(the bot's04308shape and your reproduction). Skip set is now built fromfilterMutationCommandsresults. MutationsInterpreter::performRequiredConversionsnull skip. Confirmed atIMergeTreeReader.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-existingmaterializeLOGICAL_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
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.
Cherry pick #105847 to 26.4: Fix on-fly mutation LowCardinality pass-through column conversion
…ough column conversion
Cherry pick #105847 to 26.5: Fix on-fly mutation LowCardinality pass-through column conversion
…ough column conversion
Backport #105847 to 26.3: Fix on-fly mutation LowCardinality pass-through column conversion
Backport #105847 to 26.4: Fix on-fly mutation LowCardinality pass-through column conversion
Backport #105847 to 26.5: Fix on-fly mutation LowCardinality pass-through column conversion
|
Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/1818 Labels added:
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. |
|
Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/1846 Labels added:
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. |
…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]>
…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]>
…y pass-through column conversion
…5847 Backport ClickHouse#105847 to 26.4: Fix on-fly mutation LowCardinality pass-through column conversion
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]>
Linked issues
On-fly mutations with a pending
ALTER MODIFY COLUMN <c> LowCardinality(...)queued after anUPDATE/DELETEleft the pass-through columns (those the mutation chain never overwrites) in their on-disk types while the block header already advertised the post-MODIFYmetadata types. Downstream operators that key off the declared type then tripped on the mismatch:MergingSortedTransform'sColumnLowCardinality::insertFrom→Code 44 Expected ColumnLowCardinality, got StringNativeWriter'stypeid_cast<ColumnLowCardinality>→Code 49 LOGICAL_ERROR Bad cast from type DB::ColumnString to DB::ColumnLowCardinalityexecuteWithoutLowCardinalityColumns→ SEGV on a non-LC columnAlterConversions::getMutationStepscorrectly disablesperform_alter_conversionsfor 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 theUPDATEis 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::executeActionsBeforePrewherethen runsperformRequiredConversionswith 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/DELETEchain returned byfilterMutationCommandsfor the currentread_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 throughperformRequiredConversions. Commands dropped byfilterMutationCommands(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 COLUMNafter a lightweightDELETEfails when soft-deleted rows hold unconvertible values; out of scope here.)Changelog category (leave one):
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::ColumnLowCardinalityerrors whenapply_mutations_on_fly = 1is used on a table with pending on-flyUPDATE/DELETEmutations queued before anALTER MODIFY COLUMN ... LowCardinality(...)mutation.Documentation entry for user-facing changes
Version info
26.6.1.60126.5.3.20,26.4.5.27,26.3.14.21