Skip to content

Fix LOGICAL_ERROR in on-fly mutation prewhere when reading an overwritten LowCardinality source column - #107475

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-on-fly-mutation-materialize-lc-prewhere
Jun 17, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-on-fly-mutation-materialize-lc-prewhere

Conversation

@groeneai

@groeneai groeneai commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #105847

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 LOGICAL_ERROR: Unexpected return type from materialize (and similar type-mismatch aborts) when apply_mutations_on_fly = 1 is used on a table with a pending on-fly UPDATE whose target column is also read as a function input by an earlier on-fly UPDATE, before an ALTER MODIFY COLUMN ... LowCardinality(...) mutation.

Description

Found by the server-side AST fuzzer (Stress test (experimental, serverfuzz, arm_release)) on master, STID 1611-483a. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=6a756730987624515ad9c08daab2b7831d343ba1&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20arm_release%29

This completes the on-fly mutation LowCardinality conversion fix from #105847, which handled the case where the overwritten column is not read by the query and explicitly left the per-step variants "to a follow-up".

Reproducer

CREATE TABLE t (id UInt64, a Nullable(String), b UInt8) ENGINE = MergeTree ORDER BY id;
INSERT INTO t SELECT number, if(number % 2 = 0, NULL, toString(number)), 0 FROM numbers(100);
SYSTEM STOP MERGES t;

ALTER TABLE t UPDATE b = isNotNull(materialize(a)) WHERE 1 = 1 SETTINGS mutations_sync = 0, alter_sync = 0;
ALTER TABLE t UPDATE a = 'x'                       WHERE 1 = 1 SETTINGS mutations_sync = 0, alter_sync = 0;
ALTER TABLE t MODIFY COLUMN a LowCardinality(Nullable(String))  SETTINGS mutations_sync = 0, alter_sync = 0;

SELECT sum(b), any(a) FROM t SETTINGS apply_mutations_on_fly = 1, optimize_functions_to_subcolumns = 0;
-- LOGICAL_ERROR: Unexpected return type from materialize. Expected LowCardinality(Nullable(String)). Got Nullable(String).

Root cause

On-fly mutation steps before 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 could fail on a value being replaced).

The conversion of a column happens once, in the reader that first reads it from disk, but the value can be consumed as a function input by a later prewhere step. When the query reads both b and a, the UPDATE a = 'x' command survives filtering, so a lands in the overwritten set and its conversion is skipped. The UPDATE b = isNotNull(materialize(a)) step's action, built against the post-MODIFY metadata, then runs materialize(a) expecting LowCardinality(Nullable(String)) but receives an on-disk Nullable(String), and aborts.

Fix

Compute, once per reader chain, the set of columns consumed as a FUNCTION / ARRAY_JOIN input by any prewhere step's action DAG (walking ALIAS chains back to the INPUT node), and keep those columns out of the conversion skip set. A column that is only overwritten and never read by an action (e.g. v in UPDATE v = '100', the case #105847 added the skip for) still skips conversion, so that behavior is preserved.

Adds a regression test 04338_on_fly_mutation_read_overwritten_lc_source.

Version info

  • Merged into: 26.6.1.935

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT sum(b), any(a) FROM t SETTINGS apply_mutations_on_fly=1, optimize_functions_to_subcolumns=0 on the reproducer table aborts every time with Unexpected return type from materialize. Expected LowCardinality(Nullable(String)). Got Nullable(String) (exact CIDB error, STID 1611-483a).
b Root cause explained? Yes. On-fly steps before a pending MODIFY skip performRequiredConversions for every overwritten column. A column is converted once, in the reader that reads it from disk; but it can be consumed by a function in a later step. Reading both b and a keeps UPDATE a='x', so a joins the overwritten set and is left on-disk Nullable(String), while the UPDATE b=isNotNull(materialize(a)) step's action (built against post-MODIFY metadata) feeds it to materialize expecting LowCardinality(Nullable(String)) -> abort.
c Fix matches root cause? Yes. The fix keeps out of the skip set exactly the columns consumed as a FUNCTION/ARRAY_JOIN input by any prewhere step (the columns whose declared post-MODIFY type the action depends on), so they are converted. It does not widen bounds, add no-random-* tags, or guard the symptom.
d Test intent preserved / new tests added? Yes. New regression test 04338_on_fly_mutation_read_overwritten_lc_source covers the reading-overwritten-source case. The three 04267/04268/04308 tests from #105847 still pass unchanged.
e Both directions demonstrated? Yes. Fails on master HEAD (build 8cc3782f, LOGICAL_ERROR); passes with the fix (build 95a23b81): sum(b),any(a)=50,x, a correctly 'x', b correctly isNotNull(original a).
f Fix is general, not a narrow patch? Yes. It addresses the conversion-vs-consumption invariant in the shared MergeTreeReadersChain read path (same path for MergeTree/ReplicatedMergeTree), scanning the whole chain rather than one step. The original "overwritten-but-not-read" case (e.g. unconvertible on-disk v before UPDATE v='100', MODIFY v UInt64) still skips conversion correctly, verified by an additional manual scenario. Not a symptom guard: the bad value is traced to its origin (the skip set wrongly including a function-consumed column) and corrected there.

Session id: cron:clickhouse-worker-slot-1:20260615-042600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @CurtizJ — could you review this? It completes the on-fly mutation LowCardinality conversion fix from #105847 (which left the per-step variants to a follow-up): a column the chain overwrites but that an earlier on-fly step still reads as a function input (materialize(a)) must keep its post-MODIFY type, so it's now excluded from the conversion skip set. Found by serverfuzz on master.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6271a23]

Summary: ✅


AI Review

Summary
  • This PR fixes a narrow on-fly mutation-chain type mismatch: when a pre-MODIFY mutation step genuinely reads a column that another on-fly step overwrites, the reader now keeps that source column in the post-MODIFY type instead of skipping conversion. The current implementation makes the skip decision order-aware, preserves the existing overwrite-before-convert behavior, and covers the prior review edge cases for query PREWHERE, dotted physical column names, and same-step self-reads. I did not find unresolved blockers or major issues.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 15, 2026
@groeneai
groeneai force-pushed the groeneai/fix-on-fly-mutation-materialize-lc-prewhere branch from 66b9d06 to 6e4dab5 Compare June 15, 2026 10:35
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (revised after the order/step-aware fix)

# Question Answer
a Deterministic repro? Yes, both directions. Original: SELECT sum(b), any(a) over UPDATE b=isNotNull(materialize(a)) / UPDATE a='x' / MODIFY a LowCardinality(Nullable(String)) aborts LOGICAL_ERROR: Unexpected return type from materialize. Regression introduced by the prior chain-wide commit: SELECT sum(b) PREWHERE v>50 over UPDATE v='100' / MODIFY v UInt64 aborts CANNOT_PARSE_TEXT: Cannot parse string 'x' as UInt64. Both fire on demand.
b Root cause explained? On-fly mutation steps run with perform_alter_conversions=false; overwritten columns skip performRequiredConversions. Conversion happens once in the reader that reads the column from disk. The prior fix collected consumed columns across the WHOLE chain, including trailing query PREWHERE steps, so a query predicate (PREWHERE v>50) pulled an overwritten column out of the skip set and forced a premature CAST('x'->UInt64) before UPDATE v='100' discards it.
c Fix matches root cause? Yes. collectColumnsConsumedByChainActions now scans only on-fly mutation steps (perform_alter_conversions==false). A mutation step's DAG is built against post-MODIFY metadata, so a column it reads must be converted; query PREWHERE/row-level-filter steps (perform_alter_conversions==true) convert at their own turn and are excluded. Confirmed the reader/step layout with DAG instrumentation, not assumption.
d Test intent preserved / new tests added? 04338 extended to cover BOTH the materialize(a) over LowCardinality case AND the overwrite-then-query-PREWHERE case the chain-wide scan regressed. No existing test weakened.
e Both directions demonstrated? Yes. Original crash and the PREWHERE v>50 regression both fail without the fix and pass with it. Also verified UPDATE a=upper(a)+MODIFY LC (mutation step reads value: still converted, correct).
f Fix is general, not a narrow patch? Yes. The discriminator (perform_alter_conversions) is the actual semantic boundary between mutation steps (need post-MODIFY type) and query steps (convert at their turn), not a patch for one query. Validated across 3 distinct shapes plus #105847's tests 04267/04268/04308 and the 03047_on_fly_mutations_* suite (non-ZK), all passing. Not a defensive guard.

Session id: cron:clickhouse-worker-slot-3:20260615-092500

@Algunenano Algunenano self-assigned this Jun 15, 2026
@Algunenano

Copy link
Copy Markdown
Member

@groeneai Does this cover all cases reported in #105947? These were pre-existing bugs that #105847 did not cover because it required major refactor of the process. I'd expect the followup, when it comes, to cover all of them

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano No. I tested every reproducer in #105947 against this branch (debug build of the PR head). Only variant 5 is fixed; the soft-delete / DELETE-then-MODIFY family is not.

#105947 variant Result on this branch Fixed here
1. lightweight DELETE id<100 then on-fly MODIFY c UInt64 Code 6 CANNOT_PARSE_TEXT on _CAST(c,'UInt64') No
1b. DELETE WHERE c='abc' then MODIFY Code 53 TYPE_MISMATCH on equals(c,'abc') No
2. lightweight DELETE then materialised MODIFY (on_fly=0) Code 341, mutation_4.txt stuck is_done=0, CANNOT_PARSE_TEXT No
3. heavyweight DELETE+MODIFY fully synced (control) 100 ['UInt64'] 100 199 already worked
4. heavyweight DELETE+MODIFY queued no sync both mutations stuck; read of c throws CANNOT_PARSE_TEXT No
5. on-fly UPDATE b=isNotNull(materialize(a)) / UPDATE a='x' / MODIFY a LC(Nullable(String)), SELECT sum(b),any(a) 50 x correct (was LOGICAL_ERROR Unexpected return type from materialize) Yes

This PR is scoped to the on-fly UPDATE-chain action-DAG mechanism only (MergeTreeReadersChain::executeActionsBeforePrewhere): when a later UPDATE overwrites a column that an earlier on-fly step reads as a function input, force that column to its post-MODIFY type instead of leaving it on-disk-typed. That is variant 5.

Variants 1/1b/2/4 share a different root, as your issue's "Suggested solution" lays out: the column-side _CAST (and the predicate-side cast) runs over soft-deleted/about-to-be-deleted rows before the row filter, in layers this PR does not touch:

  • inplaceBlockConversions.cpp convertRequiredExpressions + IMergeTreeReader::performRequiredConversions + MutateTask (apply_deleted_mask=false) -> make the column-side _CAST _row_exists-aware.
  • AlterConversions::getMutationActions builds the DAG against the post-MODIFY metadata_snapshot -> build against the part's on-disk schema to fix the predicate-side cast (variant 1b).

That is the larger refactor you mentioned #105847 deferred. How would you like to land it: keep this PR as the variant-5 fix and open a separate follow-up for the _row_exists-aware cast + on-disk-schema DAG, or fold everything into this one? I lean toward splitting (this fix is small and orthogonal), but it's your call.

@Algunenano Algunenano left a comment

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.

In general it looks good, but the PR adds handling for ALIAS and no tests for it. Same problem with ARRAY JOIN, which might not even be reachable via mutation.

@groeneai Could you please add tests that cover these corner cases? If they aren't reachable and it's dead code, it's better to remove it and add assertions instead. Otherwise people might miss read it, copy the code and treat it as correct.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished on HEAD 6e4dab51 (Finish Workflow SUCCESS). No PR-caused failures.

  • Fast test (arm_darwin) reds (01951_distributed_push_down_limit, 01952_optimize_distributed_group_by_sharding_key, 03135_keeper_client_find_commands) are pre-existing macOS-only issues unrelated to this on-fly-mutation prewhere change. 01951/01952 are the loopback-alias contamination addressed in Add loopback interface aliases on macOS to run parallel-replica remote() tests #107435 (51 hits across 46 unrelated PRs, 0 on master in 7d); 03135 is a macOS socket-connect flake.
  • Unit tests (amd_llvm_coverage) -FunctionsStress is a chronic trunk flake (167 hits / 59 PRs / 12 master in 30d).
  • CH Inc sync is the external mirror (non-gating).

Session: cron:our-pr-ci-monitor:20260615-160000

@groeneai
groeneai force-pushed the groeneai/fix-on-fly-mutation-materialize-lc-prewhere branch from 6e4dab5 to def75a0 Compare June 15, 2026 17:39
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Build caf9f46f: original crash SELECT sum(b), any(a) over materialize(a) + UPDATE a='x' + MODIFY a LowCardinality(Nullable(String)) returns 100 x (was LOGICAL_ERROR: Unexpected return type from materialize). Bot regression SELECT sum(b) ... PREWHERE v>50 over UPDATE v='100' + MODIFY v UInt64 returns 10 / any(v)=100 (was CANNOT_PARSE_TEXT).
b Root cause explained? This follow-up addresses the review point, not the original bug: collectColumnsConsumedByChainActions walked ALIAS chains and handled ARRAY_JOIN for function arguments of mutation-step DAGs. Empirically (DAG instrumentation over 38 mutation-step DAGs across materialize, nested funcs, heavy CSE, multiIf, tupleElement, arrayMap/arrayFilter lambdas, both analyzers) neither path is reachable: a mutation step binds a function argument directly to its source node (INPUT/FUNCTION/COLUMN); ALIAS appears only as a step's named output, never as a function arg. arrayJoin is rejected for mutations in MutationsInterpreter (hasArrayJoin() -> UNEXPECTED_EXPRESSION), so an ARRAY_JOIN node never reaches a mutation-step DAG (confirmed at runtime, Code 183).
c Fix matches root cause? Yes. Per the reviewer's preference for dead code: removed the ALIAS-chain walk and ARRAY_JOIN branch; collect INPUT arguments directly; added chassert(node.type != ARRAY_JOIN) and chassert(arg->type != ALIAS) documenting both invariants so future readers do not copy unverified handling. The order/step-aware logic (perform_alter_conversions filtering) is unchanged.
d Test intent preserved / new tests added? The reachable behavior is unchanged, so the existing 04338 regression test (both the materialize(a)-over-LC case and the overwrite-then-query-PREWHERE case) still passes against its reference. arrayJoin-in-mutation rejection is already covered by 02504_disallow_arrayjoin_in_mutations. The removed paths are unreachable, so they are asserted rather than tested (no behavior to assert via SQL).
e Both directions demonstrated? Yes. 04338 .sql diffs clean against .reference on the new binary; 02504_disallow_arrayjoin_in_mutations passes (Code 183 still thrown); the original crash and bot regression both pass on caf9f46f.
f Fix is general, not a narrow patch? Yes. The assertions cover all node types a mutation-step DAG argument can take; the INPUT collection is the only reachable case. Sibling reachability (lambda/CSE/tuple/multiIf, both analyzer paths) was exercised and produced zero ALIAS-as-argument and zero ARRAY_JOIN occurrences.

Session id: cron:clickhouse-worker-slot-1:20260615-170100

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano Both are dead code, so I removed the handling and replaced it with assertions (pushed in def75a0d).

Reachability evidence (DAG instrumentation over 38 on-fly mutation-step DAGs spanning materialize, nested functions, heavy CSE, multiIf, tupleElement, arrayMap/arrayFilter lambdas, and both analyzer paths):

  • ARRAY JOIN: not reachable. arrayJoin is rejected for mutations in MutationsInterpreter::addStreamsForLaterStages (dag.hasArrayJoin() -> UNEXPECTED_EXPRESSION, both analyzer paths), so an ARRAY_JOIN node never reaches a mutation-step DAG. Confirmed at runtime (UPDATE ... = arrayJoin(...) and DELETE WHERE arrayJoin(...) both throw Code 183). Already covered by 02504_disallow_arrayjoin_in_mutations.
  • ALIAS as a function argument: not reachable. A mutation step binds a function argument directly to its source node (INPUT, FUNCTION, or COLUMN). ALIAS nodes appear only as a step's named output (e.g. 9 : ALIAS (8) -> b, Output nodes: 9 1), never as a function argument. Zero ALIAS-as-argument occurrences across all 38 dumps.

So collectColumnsConsumedByChainActions now collects INPUT arguments directly and asserts both invariants:

chassert(node.type != ActionsDAG::ActionType::ARRAY_JOIN);
...
chassert(arg->type != ActionsDAG::ActionType::ALIAS);

The reachable behavior is unchanged, so 04338 still passes both directions (the materialize(a)-over-LC crash case and the overwrite-then-PREWHERE case), and 02504 still rejects arrayJoin.

…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.

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): their action DAG is always built against
the post-MODIFY metadata type, so a column they read 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).

The consumed set is keyed by NameAndTypePair::getNameInStorage, the same
subcolumn-aware key the skip set in executeActionsBeforePrewhere compares
against. Each function-input name from an action DAG is resolved through the
readers' column lists to that storage key. A physical column whose name
contains dots (e.g. info.name) keeps its exact name, while a real subcolumn
(info.name where info is a Tuple/Nested column) maps to its parent storage
column info. Keying by the part before the first dot would store a physical
info.name as info, miss it in the skip set, and reintroduce the same
materialize type mismatch.

The arrayJoin and ALIAS-as-function-argument cases are not reachable in a
mutation step's DAG (arrayJoin is rejected for mutations in MutationsInterpreter
because it changes the row count; a mutation step binds function arguments
directly to source nodes, with ALIAS appearing only as a step's named output),
so they are guarded with assertions rather than handled.
@groeneai
groeneai force-pushed the groeneai/fix-on-fly-mutation-materialize-lc-prewhere branch from def75a0 to 27155e4 Compare June 15, 2026 18:39
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On the prior PR head a physical column literally named info.name: CREATE TABLE t (id UInt64, ``info.name`` Nullable(String), b UInt8) ENGINE=MergeTree ORDER BY id; insert 100 rows; SYSTEM STOP MERGES; UPDATE b = isNotNull(materialize(``info.name``)), UPDATE ``info.name`` = 'x', MODIFY COLUMN ``info.name`` LowCardinality(Nullable(String)) (all async); then SELECT sum(b), any(``info.name``) SETTINGS apply_mutations_on_fly=1, optimize_functions_to_subcolumns=0 aborted every time with LOGICAL_ERROR: Unexpected return type from materialize. Expected LowCardinality(Nullable(String)). Got Nullable(String). FUNCTION materialize(info.name : 1).
b Root cause explained? The consumed-set was keyed via Nested::extractTableName(input_name), which splits on the first dot and stores info for an input named info.name. The skip check in executeActionsBeforePrewhere keys columns by NameAndTypePair::getNameInStorage(), which is subcolumn-aware: for a physical column literally named info.name (no subcolumn delimiter) it returns the full info.name. So info.name was overwritten and in the skip set but absent from the consumed set, its conversion to the post-MODIFY LC type was skipped, and materialize(info.name) received on-disk Nullable(String) while its declared input was LowCardinality(Nullable(String)), aborting.
c Fix matches root cause? Yes. The consumed set is now keyed with the same storage key the skip set uses. Each DAG function-input name is resolved through the readers' own column lists (IMergeTreeReader::getColumns()), mapping the read name to NameAndTypePair::getNameInStorage(). A physical dotted column keeps its exact name info.name; a real subcolumn info.name (where info is Tuple/Nested) maps to parent info, by construction matching the skip set on both sides. The first-dot split is removed.
d Test intent preserved / new tests added? Yes. Added a dotted-physical-column block to 04338_on_fly_mutation_read_overwritten_lc_source (info.name physical column with the same UPDATE/UPDATE/MODIFY chain) that FAILS on the prior head and PASSES with the fix. The existing 04338 cases (plain column, overwrite-then-PREWHERE) are unchanged and still pass.
e Both directions demonstrated? Yes. Prior head (build caf9f46f): the info.name repro aborts with the materialize LOGICAL_ERROR. Fixed binary (build 14fcdb2d): sum(b), any(``info.name``) returns 50 x; direct reads return the expected rows; 04338 passes (.sql vs .reference) in an isolated database. The original plain-column case (50 x) and the overwrite-then-PREWHERE case (5, 100 5) also still pass.
f Fix is general, not a narrow patch? Yes. The fix targets the shared keying invariant rather than special-casing dots: both the consumed set and the skip set now derive their key from the reader's getNameInStorage(), so physical-dotted-names and real subcolumns are handled uniformly. Verified the real-subcolumn path: a genuine Tuple subcolumn maps to its parent (info); an on-fly UPDATE that references a Tuple subcolumn as a function input is rejected earlier in MutationsInterpreter (NO_SUCH_COLUMN), so that path is not reachable via on-fly mutation and is unaffected. The arrayJoin / ALIAS-as-arg branches remain guarded by assertions (proven unreachable in mutation DAGs in the prior revision).

Session id: cron:clickhouse-worker-slot-4:20260615-181500

The previous version collected every column consumed as a function input by
any on-fly mutation step (chain-wide) and forced its conversion. That over-forces
when the column is overwritten before any later step consumes it. An UPDATE
compiles to `if(cond, _CAST(expr), C)` and reads the old `C`, so a non-constant
`UPDATE v = toString(id + 100)` makes the overwrite step self-consume `v`; the
chain-wide set then forced a conversion of the on-disk value before the UPDATE
replaced it, casting an unconvertible `'x'` to `UInt64` (CANNOT_PARSE_TEXT).

Decide per column in chain (mutation version) order: the first step that
references a column wins. If that step overwrites it, leave it skipped (its
on-disk value is discarded there); if that step only consumes it as a function
input, force its conversion (the consumer reads the on-disk value and needs the
post-MODIFY type). A later consumer never matters: it reads the value the
overwriting step already produced. Overwrite wins within a step, so the UPDATE
self-consumption stays skipped.

This keeps the LowCardinality fix (consumer step runs before the overwriter) and
fixes the reverse ordering. Extends 04338 with a regression case.

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

Copy link
Copy Markdown
Collaborator Author

@Algunenano

Done. The ALIAS and ARRAY JOIN branches are not reachable in a mutation step's DAG, so I removed the handling and replaced it with assertions (your option b):

  • ARRAY JOIN: MutationsInterpreter rejects arrayJoin in mutations (it changes the row count), so a mutation step's DAG never contains an ARRAY_JOIN node. Guarded with chassert(node.type != ActionsDAG::ActionType::ARRAY_JOIN).
  • ALIAS as a function argument: a mutation step binds function arguments directly to their source node (INPUT, FUNCTION, or COLUMN); ALIAS only appears as a step's named output, never as an argument. Guarded with chassert(arg->type != ActionsDAG::ActionType::ALIAS).

I verified both empirically by dumping the per-step action DAGs of the on-fly mutation chains in the tests: function arguments are always INPUT/FUNCTION/COLUMN, never ALIAS, and no ARRAY_JOIN node ever appears.

Separately, the bot flagged a real over-forcing in the chain-wide consumed set; I made the exclusion order-aware in the same push (details in the inline reply). The new commit keeps the LowCardinality fix and adds a regression case for the reverse ordering.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit eec7ef5, addressing the per-step ordering bug)

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (id UInt64, v String, b UInt8) ENGINE=MergeTree ORDER BY id; INSERT ... 'x' ...; UPDATE v = toString(id+100); UPDATE b = isNotNull(materialize(v)); MODIFY COLUMN v UInt64; SELECT v,b ... apply_mutations_on_fly=1 aborts every time with CANNOT_PARSE_TEXT: Cannot parse string 'x' as UInt64.
b Root cause explained? UPDATE v = expr compiles to if(cond, _CAST(expr), v), so the overwriting step itself reads the old on-disk v. The previous chain-wide consumed set put v in columns_consumed_by_chain_actions; the skip guard then un-skipped v at its disk reader and performRequiredConversions cast the about-to-be-discarded on-disk 'x' to the post-MODIFY UInt64, which throws.
c Fix matches root cause? Yes. The collection is now per column in chain (mutation-version) order: the first step that references a column decides it. Overwrite -> leave skipped; consume-as-input -> force conversion. Overwrite wins within a step, so the UPDATE self-consumption no longer forces a conversion. Targets the exact mechanism in (b).
d Test intent preserved / new tests added? Yes. The LowCardinality assertions and the existing PREWHERE/dotted-column cases in 04338 are unchanged and still pass. Added a new section to 04338 covering the non-constant overwriter-before-consumer ordering.
e Both directions demonstrated? Yes. The new test section aborts with CANNOT_PARSE_TEXT on the pre-fix binary (044ca218) and passes (100 1, 101 1) on the fixed binary (d7b55860). Full 04338 passes 5/5.
f Fix is general, not a narrow patch? Yes. The fix is a strict refinement of the prior behavior (the new forced-conversion set is a subset of the old one), so it can only remove premature conversions, never introduce a new type mismatch. The order-aware rule covers both orderings (consumer-before-overwriter and overwriter-before-consumer) and same-step self-consumption, not just the one query that crashed.

Session id: cron:clickhouse-worker-slot-2:20260615-191000

…rsion

The previous order-aware skip used "overwrite wins within a step" so that the
self-reference an UPDATE has on its target column did not force conversion. That
tie-break was too broad: it also dropped a genuine same-step read of the column.

MutationsInterpreter lowers UPDATE col = expr WHERE cond to
_CAST(if(cond, _CAST(expr, type), col), type). The bare col argument of that if
is a synthetic keep-old-value fallback (the value for unmatched rows) and must
not force conversion. But col can also be read genuinely in the same step, for
example UPDATE col = materialize(col): there col is consumed by materialize(col)
whose action was built for the post-MODIFY type, so the on-disk value must still
be converted. With overwrite winning, col stayed skipped and materialize ran on
the on-disk type, aborting with
LOGICAL_ERROR: Unexpected return type from materialize.

Now the per-step scan locates the synthetic if node for each overwritten column
(descend the assignment output through the named ALIAS and any outer _CAST
wrappers; match if(cond, then, INPUT col) whose third argument is the bare input
of that column) and ignores only that one fallback edge. Every other reference,
in cond or in expr, counts as a genuine consume. Within a step a genuine consume
now wins over the overwrite; across steps the first reference still decides, so
the earlier overwrite-before-consumer case stays skipped.

Adds a regression case (t_self_read_overwrite) to
04338_on_fly_mutation_read_overwritten_lc_source: UPDATE a = materialize(a) then
MODIFY a LowCardinality(Nullable(String)), read with apply_mutations_on_fly = 1.
It aborts before this change and passes after.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 6271a23)

# Question Answer
a Deterministic repro? Yes. UPDATE a = materialize(a) WHERE 1 then MODIFY a LowCardinality(Nullable(String)), SELECT any(a) ... apply_mutations_on_fly = 1, optimize_functions_to_subcolumns = 0 aborts every time on the reviewed head (debug Build ID D7B55860).
b Root cause explained? The UPDATE step DAG is _CAST(if(cond, _CAST(materialize(a)), a), type). a is referenced both genuinely (by materialize(a), whose action was built for the post-MODIFY type) and synthetically (as the if keep-old fallback). The prior "overwrite wins within a step" tie-break excluded a from columns_consumed_by_chain_actions on the strength of the synthetic reference, so conversion was skipped and materialize ran on the on-disk Nullable(String) against a DAG built for LowCardinality(Nullable(String)).
c Fix matches root cause? Yes. The scan now excludes only the one synthetic edge (the if's third argument, located by descending the assignment output through the ALIAS and outer _CAST wrappers) and counts every other reference as a genuine consume; a genuine same-step consume forces conversion. It targets exactly the over-broad tie-break the bot identified.
d Test intent preserved / new tests added? Added t_self_read_overwrite to 04338_on_fly_mutation_read_overwritten_lc_source for the same-step self-read. All existing sections (LC consumer-before-overwriter, query PREWHERE, dotted physical column, cross-step overwrite-before-consume) are unchanged and still pass.
e Both directions demonstrated? Yes. The new section aborts on the pre-fix binary (Build ID D7B55860, source-only stash + rebuild) and the full 04338 passes on the fixed binary (Build ID 101F51B7), output matching the reference.
f Fix is general, not a narrow patch? The exclusion is driven by the DAG shape MutationsInterpreter emits for any UPDATE col = expr WHERE cond, so it covers reads in cond and in expr (not just materialize), any number of overwritten columns, and the dotted-physical-column key path. It is not a guard at the crash site: the rule is "force conversion for a genuine pre-overwrite read, skip only the synthetic keep-old fallback", applied uniformly across steps in mutation-version order. No sibling code path implements the same exclusion.

Session id: cron:clickhouse-worker-slot-1:20260615-212300

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 6271a231daa9 (Finish Workflow SUCCESS). No PR-caused failures. Disposition of every red check:

  • Integration tests (amd_asan_ubsan db disk old analyzer 3/6, 5/6; arm_binary distributed plan 1-4/4; amd_msan 3/6; amd_llvm_coverage 1-5/5; amd_binary_excluded_from_llvm): job-summary-only rows (0 test rows produced) = harness/infra aborts. The batches that actually ran (old analyzer 1/2/4/6, msan 1/2/4/5/6, all coverage stateless) are 0 fails.
  • Stress test (arm_asan_ubsan, s3) "Hung check failed": chronic flake across 13+ unrelated PRs in 30d (1 hit each); stack is in DataTypeDateTime64 ctor, unrelated to the MergeTreeReadersChain read-path change here.
  • Bugfix validation (functional tests) OOM in dmesg / Lost forever for SharedMergeTree / S3_ERROR / Lost s3 keys / Exception in test runner: standard infra meta-rows present identically across the whole PR queue.

Stateless (incl. on-fly mutation / PREWHERE / LowCardinality), unit tests, AST/BuzzHouse fuzzers, builds: all green.

@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.10% 85.10% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 82/82 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@Algunenano Algunenano left a comment

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.

Looks good. This is getting quite complex already but I hope that a larger refactor (#105947) will allow us to simplify things

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.

4 participants