Skip to content

Fix mutation failure when MATERIALIZED column depends on EPHEMERAL column - #99281

Merged
tiandiwonder merged 14 commits into
ClickHouse:masterfrom
Onyx2406:fix/mutation-ephemeral-materialized
Mar 24, 2026
Merged

tiandiwonder merged 14 commits into
ClickHouse:masterfrom
Onyx2406:fix/mutation-ephemeral-materialized

Conversation

@Onyx2406

@Onyx2406 Onyx2406 commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed ALTER TABLE UPDATE/DELETE failing with Missing columns error when a table has a MATERIALIZED column whose expression depends on an EPHEMERAL column.

Documentation entry for user-facing changes

  • Documentation is not required (bug fix)

What this PR does

When a table has:

c1 String EPHEMERAL,
c2 String MATERIALIZED tryBase64Decode(c1),
c3 Bool

Running ALTER TABLE t UPDATE c3 = false WHERE c2 = 'Hello World!' fails with:

Missing columns: 'c1' while processing: 'tryBase64Decode(c1)'

Root cause: During mutations, MutationsInterpreter::prepare() tries to analyze MATERIALIZED column expressions to detect dependencies. It calls TreeRewriter::analyze() with all_columns which excludes EPHEMERAL columns (they're not physical/on-disk). When the MATERIALIZED expression references an EPHEMERAL column, TreeRewriter throws because it can't find it.

Fix: Before analyzing MATERIALIZED expressions, include EPHEMERAL columns in the analysis set (so TreeRewriter can resolve them), then check if any required source columns are EPHEMERAL. If so, skip recalculating that MATERIALIZED column — its on-disk value is already correct from INSERT time, and we can't read EPHEMERAL data from disk anyway.

Changes (32 insertions, 1 file + tests)

src/Interpreters/MutationsInterpreter.cpp:

  • Collect EPHEMERAL column names from columns_desc
  • Build all_columns_with_ephemeral that includes EPHEMERAL columns for TreeRewriter analysis
  • After analyzing each MATERIALIZED expression, check if it depends on any EPHEMERAL column
  • If yes, skip adding it to column_to_affected_materialized (don't try to recalculate it)

Test plan

  • New stateless test 04044_mutation_ephemeral_materialized.sql:
    • Creates table with EPHEMERAL + MATERIALIZED + regular columns
    • INSERT with EPHEMERAL value, verify MATERIALIZED computed correctly
    • UPDATE regular column WHERE MATERIALIZED = value (was failing)
    • DELETE WHERE MATERIALIZED = value (was failing)
    • Verifies data correctness after each operation
  • CI (full test suite)

Fixes #84981
Related: #68839, #71793


Note

Medium Risk
Touches mutation preparation logic for MATERIALIZED dependency analysis, which can affect which columns get recomputed during ALTER UPDATE/DELETE. While scoped, incorrect dependency handling could lead to missed recalculations or stale on-disk values.

Overview
Fixes ALTER TABLE ... UPDATE/DELETE failures when a MATERIALIZED column expression references an EPHEMERAL column by including ephemeral columns in the dependency-analysis input to TreeRewriter.

During mutation planning, MATERIALIZED columns that depend on EPHEMERAL inputs are now excluded from recalculation, with a warning logged if a mixed dependency (ephemeral + regular) could become stale. Adds a stateless test (04044_mutation_ephemeral_materialized.sql) covering update/delete, mixed materialized columns, mixed-dependency staleness behavior, and the lightweight update path.

Written by Cursor Bugbot for commit 7afd5ad. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.4.1.179

When a MATERIALIZED column's expression depends on an EPHEMERAL column,
skip recalculating it during mutations. EPHEMERAL columns are only
available at INSERT time and cannot be read from disk, so the on-disk
MATERIALIZED value is already correct.

Fixes ClickHouse#84981
The stage that recalculates MATERIALIZED columns was recalculating ALL
of them even if only some were affected. This caused crashes when an
unaffected MATERIALIZED column depends on an EPHEMERAL column. Now
only recalculate columns in the affected_materialized set.
@tiandiwonder tiandiwonder self-assigned this Mar 11, 2026
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Mar 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b426ebe]

Summary: ✅

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 12, 2026
- Combine ephemeral column collection into single loop (tiandiwonder)
- Add LOG_WARNING when MATERIALIZED depends on both EPHEMERAL and
  regular columns being updated (stale value detection)
- Add no-fasttest tag to fix CI failure
- Add test case 3: mixed-dependency MATERIALIZED (EPHEMERAL + ordinary)
- Add test case 4: lightweight DELETE path

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

{
if (column.default_desc.kind == ColumnDefaultKind::Materialized)
if (column.default_desc.kind == ColumnDefaultKind::Materialized
&& affected_materialized.contains(column.name))

@clickhouse-gh clickhouse-gh Bot Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Restricting recomputation to affected_materialized can leave transitive MATERIALIZED dependencies stale. Example: m1 MATERIALIZED x + 1, m2 MATERIALIZED m1 + 1; ALTER TABLE ... UPDATE x = ... marks only m1 as affected, so m2 is not recomputed after this change. Please either compute the transitive closure of affected MATERIALIZED columns here or keep recomputing all MATERIALIZED columns in this stage.

@tiandiwonder tiandiwonder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

please fix the test failure.

…fix test

- Shorten ephemeral check using std::ranges::any_of (tiandiwonder)
- Rename 'required' to 'required_columns' (tiandiwonder)
- Add no-fasttest explanation comment (tiandiwonder)
- Replace Case 4 with lightweight UPDATE using proper settings (tiandiwonder)
- Fix column order in mixed-dep test to match table definition

DROP TABLE t_mixed_materialized;

-- Case 3: Mixed-dependency MATERIALIZED column (EPHEMERAL + ordinary in same expression).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please add one more case for transitive MATERIALIZED dependencies (for example x, m1 MATERIALIZED x + 1, m2 MATERIALIZED m1 + 1 with ALTER ... UPDATE x = ...). This test currently covers direct dependencies, but it does not guard against stale second-level MATERIALIZED columns.

@rienath

rienath commented Mar 13, 2026 •

Copy link
Copy Markdown
Member

One of the red CI checks might've been because of #98605, which is now fixed. Merging master to remove the noise

…no-fasttest

Lightweight UPDATE requires additional settings (apply_patch_parts) and
ReplicatedMergeTree complexity that is not the focus of this bug fix.
The core fix is in MutationsInterpreter which is tested via ALTER TABLE
UPDATE. Case 4 now uses ALTER TABLE UPDATE with block tracking settings
to match the original issue schema.
tryBase64Decode is unavailable in Fast test builds (-DENABLE_LIBRARIES=0).
Use reverse() which is always built-in.

DROP TABLE t_mixed_dep;

-- Case 4: Same schema as the original issue #84981 (with block tracking columns)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This case is labeled as the original issue #84981, but it still uses ALTER TABLE ... UPDATE. The issue repro uses lightweight UPDATE ... SET ... with allow_experimental_lightweight_update = 1.

Please add (or replace this case with) a lightweight UPDATE test that mirrors the repro syntax, so this PR protects the exact user-facing path that previously raised Missing columns.

The LOG_WARNING about stale MATERIALIZED column goes to stderr,
causing the test framework to mark it as FAIL. Use send_logs_level
to suppress it.
"during this mutation — the on-disk value may become inconsistent. "
"To fix this, re-INSERT the affected rows.",
column.name);
continue;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

continue here removes this MATERIALIZED column from column_to_affected_materialized, so validateUpdateColumns no longer sees that updating x affects this column.

That bypasses the existing key-safety guard in validateUpdateColumns (the check that blocks updates when an updated source affects a MATERIALIZED key column). For schemas like m MATERIALIZED f(ephemeral, x) with m in ORDER BY, ALTER ... UPDATE x = ... now succeeds and leaves m stale.

Please keep dependency tracking for non-EPHEMERAL inputs (or throw an explicit exception) so key-column protection still triggers.

INSERT INTO t_mixed_dep (c1, c3) VALUES ('abcdef', 'hello');
SELECT c2, c3 FROM t_mixed_dep;

ALTER TABLE t_mixed_dep UPDATE c3 = 'world' WHERE c3 = 'hello' SETTINGS send_logs_level = 'error';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Case 3 currently forces send_logs_level = 'error', which suppresses the new warning emitted for mixed EPHEMERAL/regular dependencies. As a result, this test only checks the stale-data result, but not the only user-visible safeguard (the warning).

Please add a check that the warning is actually emitted (for example via an integration test that inspects logs), or avoid suppressing logs here and validate the message in a test that can assert it.

@clickhouse-gh

clickhouse-gh Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.70% -0.10%
Functions 23.90% 23.90% +0.00%
Branches 76.30% 76.30% +0.00%

PR changed lines: PR changed-lines coverage: 100.00% (42/42, 0 noise lines excluded)
Diff coverage report
Uncovered code

@alexey-milovidov

alexey-milovidov commented Mar 23, 2026 •

Copy link
Copy Markdown
Member

Now all green (except the private sync).
@tiandiwonder @rienath, ok to merge?

@tiandiwonder

Copy link
Copy Markdown
Contributor

Now all green (except the private sync). @tiandiwonder @rienath, ok to merge?
Yes, please.

@tiandiwonder
tiandiwonder added this pull request to the merge queue Mar 24, 2026
Merged via the queue into ClickHouse:master with commit cc8c93b Mar 24, 2026
159 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 24, 2026
@zlareb1

zlareb1 commented Mar 24, 2026

Copy link
Copy Markdown
Member

@Onyx2406 @tiandiwonder please check #100613

nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Aug 24, 2026
…UPDATE

`MutationsInterpreter::prepare` collected the MATERIALIZED columns to recalculate
from direct dependencies only: an edge `dependency -> materialized column` was
recorded just for the dependencies present in `updated_columns`. A MATERIALIZED
column that reads another MATERIALIZED column therefore never entered
`affected_materialized`, and the guard added in ClickHouse#99281 skipped it, so its on-disk
value stayed frozen at what `INSERT` computed, no matter how many mutations ran.

Build the whole MATERIALIZED dependency graph instead, walk it from the columns the
command updates, and group the reachable columns by longest-path dependency level.
Emitting one mutation stage per level also makes the values correct rather than
merely refreshed: stage N reads the output of stage N-1, so an expression sees the
recalculated value of the MATERIALIZED column it depends on instead of the stale
on-disk one. That was the second half of the problem, reported separately as ClickHouse#50237.
The walk still excludes a MATERIALIZED column that reads an EPHEMERAL column, which
is what ClickHouse#99281 was about: such a column cannot be recalculated from disk. A column
downstream of it is only skipped when every path to it goes through it; one that also
reads an updated column directly is still recalculated, from the stored value.

`validateUpdateColumns` now receives the same transitive closure, so an UPDATE that
reaches a MATERIALIZED key column through another MATERIALIZED column is rejected
with `CANNOT_UPDATE_COLUMN`, as the direct case already was. Without it the
recalculation would newly break the sort order of such a table.

Recalculated MATERIALIZED columns also enter skip-index, projection and dependency
analysis. They change data without being named in the query, so the rebuild
predicates never fired for them and a projection or skip index over such a column
kept answering from pre-mutation values. This part is pre-existing and applies to a
directly recalculated column as well, but leaving it would make the fix above
inconsistent: correct on disk, wrong through a projection.

`AlterConversions::addColumnsRequiredForMaterialized`, which decides what an on-fly
mutation has to read, looked one level deep the same way, so reading only the deepest
column of a chain returned its stale value while reading the whole chain returned the
recalculated one. It now follows the chain, pulling in an intermediate MATERIALIZED
column when an updated column is reachable through it. It also analysed default
expressions against physical columns only, so reading a MATERIALIZED column that
mentions an EPHEMERAL one failed with `UNKNOWN_IDENTIFIER` while a mutation was
pending; EPHEMERAL columns now enter the analysis set as they already do in
`MutationsInterpreter::prepare`.

Closes: ClickHouse#100613
Closes: ClickHouse#50237

Co-Authored-By: Claude Opus 5 <[email protected]>
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.

Lightweight updates fail when a table has a MATERIALIZED column whose value depends on an EPHEMERAL column

6 participants