Skip to content

Recalculate TTL when a mutation updates a DELETE WHERE column - #110648

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-ttl-delete-where-mutation-recalc
Aug 17, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-ttl-delete-where-mutation-recalc

Conversation

@groeneai

@groeneai groeneai commented Jul 16, 2026 •

Copy link
Copy Markdown
Collaborator

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 a TTL ... DELETE WHERE <cond> never removing rows that started matching <cond> because of an ALTER TABLE ... UPDATE on a column referenced in the WHERE. The mutation now recalculates the row TTL, so the newly matching expired rows are deleted instead of being silently retained.

Description

Closes: #110600

A TTL <time> DELETE WHERE <cond> never dropped rows that started satisfying <cond> as a result of an ALTER TABLE ... UPDATE mutation. The per-row drop decision is stored per part in rows_where_ttl_info, and StorageInMemoryMetadata::getColumnDependencies only tracked the columns of the TTL time expression (expression_columns), not the columns of the WHERE condition (where_expression_columns). So updating a WHERE-referenced column produced no TTL_EXPRESSION dependency, MutationsInterpreter skipped TTL recalculation, and the mutated part kept its pre-mutation (empty) rows_where_ttl_info. The rows were expired and matched WHERE but were never removed, not even by OPTIMIZE TABLE ... FINAL, until an explicit MATERIALIZE TTL. This breaks the soft-delete-then-TTL-purge pattern used for GDPR-style retention (silent data retention).

Fix: also add each rows-where TTL's where_expression_columns to the mutation dependency set, so an ALTER UPDATE touching them triggers a TTL recalculation. Removes the stale //TODO what about rows_where_ttl and group_by_ttl ??.

On the group_by_ttl half of that TODO: GROUP BY TTL reads live column values at merge time and is gated only on the (unchanged) time expression, and its GROUP BY key columns are part of the sort key and cannot be UPDATEd (CANNOT_UPDATE_COLUMN). Updating a SET-source column already produces the correct aggregated result with no fix, so there is no reproducible bug there; no code change was made for it.

New regression test 04546_ttl_delete_where_recalc_after_update. Verified both directions on a debug build: without the fix the table keeps all 3 rows after the mutation and OPTIMIZE FINAL; with the fix the 2 flagged expired rows are deleted immediately.

Version info

  • Merged into: 26.8.1.1545 (included in 26.8 and later)

A `TTL <time> DELETE WHERE <cond>` never dropped rows that started matching
<cond> as a result of an `ALTER TABLE ... UPDATE`. The drop decision is stored
per part in rows_where_ttl_info, and StorageInMemoryMetadata::getColumnDependencies
only tracked the columns of the TTL time expression, not the columns of the WHERE
condition. So updating a WHERE-referenced column produced no TTL_EXPRESSION
dependency, MutationsInterpreter skipped TTL recalculation, and the mutated part
kept its pre-mutation (empty) rows_where_ttl_info. The rows were expired and
matched WHERE but were never removed, not even by OPTIMIZE FINAL, until an
explicit MATERIALIZE TTL. This breaks the soft-delete-then-TTL-purge pattern used
for GDPR-style retention (silent data retention).

Fix: also add the WHERE-expression columns of each rows-where TTL to the mutation
dependency set, so an ALTER UPDATE touching them triggers a TTL recalculation.

Closes ClickHouse#110600
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE ... TTL d+INTERVAL 1 SECOND DELETE WHERE should_delete=1, insert 3 expired-but-unflagged rows, ALTER UPDATE should_delete=1 WHERE val<=2 SETTINGS mutations_sync=2, OPTIMIZE FINAL: baseline keeps all 3 rows every run; the fix deletes the 2 flagged rows every run.
b Root cause explained? The DELETE WHERE drop set is stored per part in rows_where_ttl_info. getColumnDependencies added only the TTL time expression's columns, not where_expression_columns. Updating a WHERE-only column produced no TTL_EXPRESSION dependency, so MutationsInterpreter skipped TTL recalc and the mutated part inherited the pre-mutation (empty) info; TTL merges then never re-examine it.
c Fix matches root cause? Yes. Adds each rows-where TTL's where_expression_columns to the dependency set, directly producing the missing TTL_EXPRESSION dependency so the mutation recalculates TTL.
d Test intent preserved / new tests added? New regression test 04546_ttl_delete_where_recalc_after_update added; no existing test weakened.
e Both directions demonstrated? Yes. Baseline binary: 3 rows remain after mutation + OPTIMIZE FINAL (bug). Fixed binary: 1 row remains (the unflagged val=3). Confirmed via clickhouse-local and a real server.
f Fix is general across code paths? Yes. The single gap was in getColumnDependencies (the one function deciding TTL recalculation for mutations); the sibling GROUP BY TTL path was audited (see g) and needs no change. Not a symptom guard.
g Fix generalizes across inputs? Audited the group_by_ttl half of the removed TODO: GROUP BY key columns are sort-key columns and cannot be UPDATEd (CANNOT_UPDATE_COLUMN); GROUP BY SET aggregates read live values at merge and are gated on the unchanged time expression, so updating a SET-source column already gives the correct result on the baseline. No reproducible bug there, so no speculative change was made (per maintainer guidance to not ship changes without a reproducing test).
h Backward compatible? Yes. No setting default, on-disk/wire format, or validation change. The fix only widens which mutations trigger TTL recalculation (correctness); no SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. add_for_rows_ttl is reused with the same semantics; where_expression_columns is a NamesAndTypesList (same type as expression_columns), so .getNames() and the include_ttl_target full-column-filter path behave identically. No lifetime/concurrency change.

Session id: cron:clickhouse-worker-slot-1:20260716-070600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @Michicosun — could you review this? It fixes a DELETE WHERE TTL silently never applying after an ALTER UPDATE on a WHERE-referenced column: getColumnDependencies tracked only the TTL time-expression columns, not where_expression_columns, so the mutation skipped TTL recalculation and kept the part's stale (empty) rows_where_ttl_info. Fix adds the WHERE columns to the mutation dependency set. Requested by @ PedroTadim in #110600.

@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [913d565]

Summary: ✅


AI Review

Summary

This PR correctly fixes the original ALTER ... UPDATE + TTL ... DELETE WHERE retention bug and extends the same repair to MATERIALIZED chains, APPLY PATCHES, and CLEAR COLUMN. The remaining problem is that one sibling mutation entrypoint, MATERIALIZE COLUMN, still bypasses the dependency-rebuild path, so the overall invariant is not closed yet.

Findings

❌ Blockers

  • [src/Interpreters/MutationsInterpreter.cpp:990-1005] MATERIALIZE COLUMN still never seeds its rewritten column into dependency analysis. After MODIFY COLUMN ... MATERIALIZED ... and MATERIALIZE COLUMN, a DELETE WHERE TTL on that column keeps stale rows_where_ttl_info, so expired rows that now match the predicate survive even after OPTIMIZE FINAL. The same omission also skips projection / skip-index rebuilds for columns rewritten by MATERIALIZE COLUMN.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 16, 2026
@Michicosun Michicosun self-assigned this Jul 16, 2026
…HERE column

A DELETE WHERE TTL can reference a MATERIALIZED column. When an ALTER UPDATE
touches that column's source, MutationsInterpreter recomputes the MATERIALIZED
column via column_to_affected_materialized but never adds it to the dependency
analysis set, so getColumnDependencies does not see it as updated and skips TTL
recalculation. The mutated part keeps its stale rows_where_ttl_info and expired
matching rows are silently retained, even after OPTIMIZE FINAL.

Seed the recomputed MATERIALIZED columns into the dependency analysis set so the
DELETE WHERE TTL info is recalculated.

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

Copy link
Copy Markdown
Collaborator Author

Good catch — confirmed reproducible and fixed in a410565.

Root cause of this second path: an `ALTER UPDATE` on the source column of a `MATERIALIZED` column recomputes that column via `column_to_affected_materialized` in `MutationsInterpreter::prepare`, but the recomputed column was never seeded into the dependency-analysis set. So `getColumnDependencies` never saw `flag` as updated, produced no `TTL_EXPRESSION` dependency, and `TTLTransform` was skipped — the same silent-retention outcome as the direct-column case.

Fix: seed the affected `MATERIALIZED` columns into `columns_for_dependencies` before calling `getAllColumnDependencies`. Single-level, matching the scope of `column_to_affected_materialized` itself.

Verified against your SQL (debug build): the row is retained on the pre-fix binary and deleted (count 0) after the fix. Extended `04546_ttl_delete_where_recalc_after_update` with the MATERIALIZED path.

Extend the single-hop MATERIALIZED fix to chains (m2 MATERIALIZED m1
MATERIALIZED src). column_to_affected_materialized only mapped direct
dependencies, so a base-column UPDATE never recomputed transitively
derived MATERIALIZED columns; those columns also kept a stale on-disk
value because all affected columns were recomputed in one stage,
evaluating m2 against the pre-mutation m1. Compute the transitive closure
of affected MATERIALIZED columns and recompute them in dependency-level
order (one stage per level) so each reads the freshly written value of
any affected column it depends on, and so the DELETE WHERE TTL info is
recalculated for the whole chain.
The transitive MATERIALIZED recompute added for ALTER UPDATE was missing from two
sibling paths that can also change a column a chain of MATERIALIZED columns is
derived from:

- APPLY PATCHES (read_for_patch): a patch part created before a derived chain was
  fully materialized, or by an older replica during a rolling upgrade, carries only
  the earlier hops (e.g. {src, m1} for src -> m1 -> m2 -> m3). Materializing it never
  expanded through the chain, so m2/m3 kept their stale on-disk value and a TTL
  DELETE WHERE that references m3 was not recalculated. Compute the transitive closure
  of MATERIALIZED columns derived from the patch-updated columns, seed them into the
  dependency set, and emit level-ordered recompute stages after the patched values are
  materialized.

- CLEAR COLUMN: the recompute re-evaluated every MATERIALIZED expression in a single
  stage, so a chain m2 MATERIALIZED m1 MATERIALIZED src left m2 evaluated against the
  pre-clear m1. Reuse the level-ordered recompute so each hop reads the freshly written
  value of the one it depends on.

Extract the transitive-closure and level-ordered recompute-stage emission into shared
helpers and use them for UPDATE, APPLY PATCHES and CLEAR COLUMN. Add regression tests
for a chained CLEAR COLUMN and for materializing an old-shape patch part.
…terialized projections/indices

CLEAR COLUMN was not fed into columns_for_dependencies, so a DELETE WHERE
TTL on a MATERIALIZED column derived from a cleared column kept stale
rows_where_ttl_info (execute_ttl_type stayed NONE). Seed cleared base
columns and their MATERIALIZED closure into dependency analysis.

The projection/index/statistics rebuild predicates only checked
updated_columns/changed_columns/patch_updated_columns, so a projection or
skip index reading only a derived MATERIALIZED column (m2 in src->m1->m2)
was left stale on UPDATE/APPLY PATCHES/CLEAR COLUMN and MutateTask
hardlinked the old files. Include the affected MATERIALIZED closure in
those predicates.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2b95d52

Every failure below has an owner. Neither is caused by this PR's diff (TTL/MATERIALIZED recompute in MutationsInterpreter.cpp + test).

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) — Logical error: '!part.empty()' (ASTIdentifier.cpp:48, client-side QueryFuzzer::fuzzExpressionList, STID 2508-3750) crash (pre-existing fuzzer-found, unrelated to this diff; 34 unrelated PRs / 0 master in 14d) #110677 (ours, open)
Integration tests (amd_tsan, 3/6) — test_replicated_database/test.py::test_replicated_table_structure_alter flaky (chronic: 69 master hits + 20+ unrelated PRs in 30d) #110030 (ours, open)
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260716-193000

@groeneai

groeneai commented Jul 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2b95d52

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt. None of these failures are caused by this PR's diff (TTL dependency recalculation in StorageInMemoryMetadata.cpp / MutationsInterpreter.cpp).

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) — "Client failure" + "Fuzzer exited with timeout" client-side SIGABRT in QueryFuzzer::fuzzExpressionList rewriting a {x:Identifier} param identifier into a subcolumn accessor (chassert !part.empty(), ASTIdentifier.cpp:48), a fresh trunk fuzzer regression from #110228 hitting many PRs + master on 2026-07-16 #110740 (ours, open) — "Fix AST fuzzer client crash rewriting a query-parameter identifier into a subcolumn accessor"
Integration tests (amd_tsan, 3/6) — test_replicated_database/test.py::test_replicated_table_structure_alter chronic flaky (69 master hits / 7d, 15+ unrelated PRs / 30d) #110030 (external, open) — "Fix flaky test_replicated_table_structure_alter"

Session id: cron:our-pr-ci-monitor:20260716-203000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3d9245d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Server died + Logical error: Got read request from replica A for unknown stream B (STID 5217-5b3d) with parallel replicas, a projection optimization replaces the initiator's ReadFromMergeTree with a ReadFromPreparedSource, so the empty-read-set announcement never happens and a follower requests a stream the coordinator never registered #111689 (mine, open)
Integration tests (amd_tsan, 1/6) / test_postgresql_replica_database_engine (48 tests) one server death cascading through the module's autouse setup_teardown fixture (Code: 210 Connection refused), not 48 independent test failures a fix task is created (investigating at full effort — fixing-PR link to follow here)

The Server died row and the unknown stream row are one event with one owner: the logical error
aborts the server, and the Server died row is its consequence.

The integration cascade is a trunk defect in the MaterializedPostgreSQL database engine
(materialized_tables is mutated without holding tables_mutex, so the async-metrics thread
iterates storages while a DROP destroys them, giving a heap-use-after-free). It reproduces on
master and across many unrelated PRs on the same shard. This PR's diff is
src/Interpreters/MutationsInterpreter.cpp, src/Storages/StorageInMemoryMetadata.cpp and one
stateless test, which cannot reach PostgreSQL replication or parallel-replica coordination.

Session id: cron:our-pr-ci-monitor:20260729-060000

04546 only exercised a DELETE WHERE predicate that reaches the cleared base
column through a MATERIALIZED hop. The predicate can also read the cleared
column directly, and that shape was unpinned: pristine master retains the
expired row that starts matching only after the clear, because the part keeps
its old rows_where_ttl_info.

An explicit non-default DEFAULT (7) pins which value the TTL is evaluated
against, so the assertion cannot pass by coincidence with the type default.
The multi-row fixture also keeps a matching but unexpired row, proving the TTL
info was recalculated rather than applied wholesale, and a second table checks
that a row matching neither the stored nor the default value is retained.

Verified both directions on prebuilt debug binaries: the new section alone
returns the reference output on the PR head and moves on pristine master.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_postgresql_replica_database_engine Connection-refused cascade dispositioned to a fix task on this PR's CI finish ledger: #112381 (merged), with the re-land #112382.

Root cause: #109339 added a materialized_tables traversal to DatabaseMaterializedPostgreSQL::getTablesIterator. The asynchronous-metrics thread reaches that iterator (ServerAsynchronousMetrics.cpp:447, and this database reports isExternal() == false so it is not skipped) while stopReplication clears the same map holding only handler_mutex, never tables_mutex. That is a heap-use-after-free on the stored wrappers, it killed the server, and every remaining test in the module then failed inside the autouse setup_teardown fixture with Code: 210 Connection refused. One server death per job, not N independent flaky tests.

Timeline: #109339 merged 2026-07-28 13:16 UTC, the master cascade began the same evening, #112381 reverted it 2026-07-29 01:39 UTC. Every failing build contained the introducing commit and lacked the revert. True-master runs since the revert are clean: 0 failures against 6804 passing rows across 23 distinct commits. #112382 re-lands the feature with tables_mutex taken on all materialized_tables touch points, including the swap-and-destroy-outside-the-lock form in stopReplication.

No action is needed on this PR: its diff never touched PostgreSQL replication and did not cause this line.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 738dc18

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit trunk regression, not caused by this diff (fires on master and on ~50 unrelated PRs in the same window) #112385 (mine, merged 2026-07-29 15:37Z); this build predates it, so a rerun after the next master merge picks it up
Sync - CH Inc sync (private, not actionable)

This PR's diff on this head is test-only (04546_ttl_delete_where_recalc_after_update plus its reference), so it cannot reach the failing check.

Session id: cron:our-pr-ci-monitor:20260729-170000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 738dc18

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit fails 3/3 reruns under parallel replicas on coverage builds #112385 (ours, merged 2026-07-29 15:37Z) - this build predates the fix

Session id: cron:our-pr-ci-monitor:20260729-164745

…e-mutation-recalc

# Conflicts:
#	src/Interpreters/MutationsInterpreter.cpp
groeneai added 4 commits July 30, 2026 18:04
The dependency-ordered recompute introduced for CLEAR COLUMN also narrowed the
set of columns it re-evaluates to the transitive closure of the cleared column.
That was not part of the reported problem: the review comment asked for the
chain to be evaluated in dependency order, not for fewer columns to be
recomputed.

The narrowing is user visible. A MATERIALIZED column that does not read the
cleared column kept its old value instead of being re-evaluated at its current
expression, which changes the result of CLEAR COLUMN after MODIFY COLUMN
changed that expression. 04648_mutation_statistics_type_mismatch pins the
previous behaviour and was failing on the merge.

Recompute every MATERIALIZED column with an expression again, as before, and
keep only the level ordering. A constant MATERIALIZED expression has no
dependencies and therefore never appears in materialized_column_dependencies,
so the set has to come from the column list rather than from that map.
CLEAR COLUMN rewrites every recomputable MATERIALIZED column, but the set fed
into dependency analysis and into the projection / skip index / statistics
rebuild predicates was only the transitive closure of the cleared column. A
MATERIALIZED column outside that closure was therefore rewritten in the base
part while its projection and skip index files were hardlinked unchanged, so
queries kept reading the pre-mutation value.

This is reachable without any mutation of the column itself: MODIFY COLUMN on a
MATERIALIZED expression is metadata-only and schedules no mutation, so the value
first changes on the next CLEAR COLUMN of an unrelated column.

Derive both sets from the same list of recomputable MATERIALIZED columns so they
cannot drift apart again, and drop cleared_base_columns, which is now unused.
The two tables added for the projection and skip index assertions were exposed to
three settings the test runner randomizes, each of which would have made the rows
describe a case the run never reached.

min_bytes_for_full_part_storage decides Full versus Packed storage, and a Packed
part takes the all-column mutation path, which rebuilds the artifacts regardless
of the rebuild selection under test. enable_block_number_column and
enable_block_offset_column each stop the mutation from recomputing the
MATERIALIZED columns at all, which master does too.

Pin all three, put the skip index in its own table so the index rather than a
projection has to answer the query, force the index so a silent decline cannot
pass as a base scan, and assert both directions of the index result.
/// MATERIALIZED columns recomputed by the mutation are not in updated_columns
/// but their new values still drive dependencies (e.g. a TTL DELETE WHERE that
/// references a MATERIALIZED column). Seed them so recalculation is triggered.
columns_for_dependencies.insert(all_affected_materialized.begin(), all_affected_materialized.end());

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.

MATERIALIZE COLUMN still never enters the dependency-analysis set here. That leaves a sibling mutation path with the same stale-TTL problem this PR fixes for UPDATE / APPLY PATCHES / CLEAR COLUMN.

Concrete trace:

CREATE TABLE t
(
    d DateTime,
    src UInt8,
    flag UInt8 MATERIALIZED src,
    id UInt8
)
ENGINE = MergeTree
ORDER BY tuple()
TTL d + INTERVAL 1 SECOND DELETE WHERE flag = 1
SETTINGS min_bytes_for_wide_part = 0;

INSERT INTO t (d, src, id) VALUES ('2000-01-01 00:00:00', 0, 1);
ALTER TABLE t MODIFY COLUMN flag UInt8 MATERIALIZED 1 SETTINGS mutations_sync = 2;
ALTER TABLE t MATERIALIZE COLUMN flag SETTINGS mutations_sync = 2;
OPTIMIZE TABLE t FINAL;

MATERIALIZE COLUMN rewrites flag a few lines below at 1238-1248, but in this command shape updated_columns, patch_updated_columns, clear_column_names, and all_affected_materialized are all empty, so dependencies stays empty. No TTLTransform is scheduled, the part keeps stale rows_where_ttl_info, and the expired row survives even though flag is now 1. The same omission also skips projection / skip-index rebuilds for columns rewritten by MATERIALIZE COLUMN.

I think the rewritten column names from MATERIALIZE COLUMN need to seed the same dependency/rebuild path here, plus a focused regression.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

You are right about the mechanism, and both halves reproduce. This is pre-existing master behaviour rather than something this PR changes, and an open PR already fixes it, so I am not folding it in here.

Measured on this PR's head 913d565db618 and on a pristine master build (snapshot MutationsInterpreter.cpp md5-identical to origin/master), running your repro verbatim:

assertion this PR pristine master
count() after MATERIALIZE COLUMN 1 1
flag 1 1
rows_where_ttl_info.min 1970-01-01 00:00:00 1970-01-01 00:00:00
count() after OPTIMIZE FINAL 1 1

Identical on both arms. Consistent with the code: grep -cE "^\+.*MATERIALIZE_COLUMN" over this diff is 0, and updated_columns is populated only from update_assignments, which a bare MATERIALIZE COLUMN does not carry.

The row does genuinely qualify: a following MATERIALIZE TTL drops it, and the mirror image (a row that stops matching) is retained correctly on both builds. Your trailing OPTIMIZE TABLE t FINAL does not hide it either, which is worth noting because a neighbouring shape does: the part is rewritten (all_1_1_0_2 to all_1_1_1_2) and the row still survives, and a variant with no OPTIMIZE at all gives the same answer.

Your second point about projections and skip indices is also real and also pre-existing. With a projection over m UInt8 MATERIALIZED src, after MODIFY COLUMN m MATERIALIZED 9 plus MATERIALIZE COLUMN m the base column reads 9 while the projection still answers 5 (EXPLAIN indexes = 1 confirms ReadFromMergeTree (p) serves it), and a forced minmax index prunes away the granule holding the new value, so count() WHERE m = 9 returns 0 against a ground truth of 1. Both are identical on pristine master. The projection case needs full part storage; packed parts answer correctly.

The fix for this is PR #99647, which seeds MATERIALIZE COLUMN targets into dependency analysis. On its build all three of these are addressed: the TTL shape is refused outright with Code: 420 ... Refused to materialize column 'flag' because the column 'flag' is used in the WHERE condition of a TTL DELETE / GROUP BY expression, the index count goes 0 to 1, and the projection answer goes 5 to 9. So there is no residual gap for me to cover, and adding the same seeding here would conflict with that PR's own changes to these predicates.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.60% 78.60% +0.00%

Changed lines: Changed C/C++ lines covered: 140/142 (98.59%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 913d565

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

No failures on this head. 174 check-runs, all completed: 156 success, 18 skipped, 0 failure.
Finish Workflow and Config Workflow are both green, and CIDB reports 0 test-level
FAIL/ERROR rows for this commit, so the owner table is empty.

The one row from my previous ledger is resolved rather than re-listed:
01666_merge_tree_max_query_limit under Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) was owned by #112385, which merged on 2026-07-29 after that build ran.
Its merge commit is now an ancestor of this head, and the test reads OK on every check that ran
it here, including 50/50 on arm_asan_ubsan, targeted. Nothing is owed for it.

No CH Inc sync row failed, and no Fast test, Style check, Bugfix validation,
Docs check or Config Workflow red, so nothing is PR-caused.

Session id: cron:our-pr-ci-monitor:20260731-003000

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 913d565

CI is fully finished on this head and there are no failing checks.

Check / test Reason Owner / fixing PR
(none) - -
CH Inc sync private sync (success) CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260809-013000

@Michicosun Michicosun removed their assignment Aug 14, 2026

@alexey-milovidov alexey-milovidov 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.

The fix is quite complex, but I glad that it exists.

@alexey-milovidov alexey-milovidov self-assigned this Aug 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 6061d1c Aug 17, 2026
178 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
CREATE TABLE t_ttl_where (d DateTime, should_delete UInt8 DEFAULT 0, val UInt32)
ENGINE = MergeTree ORDER BY tuple()
TTL d + INTERVAL 1 SECOND DELETE WHERE should_delete = 1
SETTINGS min_bytes_for_wide_part = 0;

-- every row is long past the TTL time expression, none matches the WHERE yet
INSERT INTO t_ttl_where VALUES ('2000-01-01 00:00:00', 0, 1), ('2000-01-01 00:00:00', 0, 2), ('2000-01-01 00:00:00', 0, 3);

ALTER TABLE t_ttl_where UPDATE should_delete = 1 WHERE val <= 2 SETTINGS mutations_sync = 2;
SELECT count() FROM t_ttl_where;   -- 26.2-26.7: 3, expected 1

OPTIMIZE TABLE t_ttl_where FINAL;
SELECT count() FROM t_ttl_where;   -- 26.2-26.7: 3 (rows never removed)
                                   -- 25.8: 1 (merge still applied the rows-where TTL)
                                   -- master after #110648: 1 (mutation recalculates it)

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3
  • Does not reproduce on: 25.8
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • Fix merged on master (not re-verified: tested master build predates this PR's merge — a clean verdict is not attributable to the fix). The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3.

CC component owner: @Michicosun @CurtizJ

Analysis metadata

comp-ttl · Severity P2 · Finding phase_d_pr110648

  • Verified against master build 6061d1c0df7e (aarch64)
  • Could not test: master
Introducing change: not identified
  • Secondary components: comp-mutations, comp-testing

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed the backport candidacy independently, with one correction and one prerequisite.

Affectedness. I ran your reproducer verbatim against the official per-release binaries (after_update / after_optimize / rows still carrying the flag):

binary after_update after_optimize flag rows verdict
26.7.4.50 3 3 2 reproduces
26.6.3.49 3 3 2 reproduces
26.5.7.57 3 3 2 reproduces
26.3.19.1 3 3 2 reproduces
25.8.31.5 3 1 0 does not reproduce
master 26.8.1.1569 1 1 0 fixed

Your four branches are right and excluding 25.8 is right. The master arm closes the gap you flagged: that nightly's GIT_HASH is d59f2be34ed39b45665de8c5afe3b333239befeb, which has this PR's merge commit 6061d1c0df7e as an ancestor (218 commits later), so it is a valid post-fix control. The fix commit is absent from all five release branches.

Label. One label is enough, and it is v26.3-must-backport. Running select_backport_branches from tests/ci/cherry_pick_branches.py against the live active set (26.7, 26.6, 26.5, 26.3, 25.8): v26.3-must-backport expands to exactly 26.7, 26.6, 26.5, 26.3. pr-must-backport would also pull in 25.8, which is not affected.

Prerequisite, and this is the part worth acting on. The cherry-pick is not clean, and resolving it in favour of this PR does not compile on any of the four branches. written_by_stage and columns_written_by_stages in MutationsInterpreter.cpp are not from this PR, they come from #112009 ("Build only the statistics a mutation is supposed to recompute", merged 2026-07-29), which is on master and on none of the release branches. Checking declaration and use separately in the naively resolved file:

branch written_by_stage used bool written_by_stage declared NameSet columns_written_by_stages declared
26.7 yes no no
26.6 yes yes no
26.5 yes yes no
26.3 yes yes no

Stacking fixes it: #112009 cherry-picks cleanly onto 26.7, and with it applied this PR then applies cleanly, touching exactly its own 4 files (+581/-59) with every symbol present. #112009 conflicts on 26.6, 26.5 and 26.3 (and additionally in MutateTask.cpp on 25.8), so those need manual resolution on the cherry-pick PR either way.

So the request is: label #112009 with v26.3-must-backport first, then this PR with the same label. Labelling this PR alone produces four cherry-pick PRs that cannot build.

Conflict counts in MutationsInterpreter.cpp for this PR, if useful for sizing: 26.7 one hunk, 26.6 six, 26.5 six, 26.3 ten. Test number 04546_ttl_delete_where_recalc_after_update is free on all four and every setting the test uses exists on all four.

I am not authoring release-branch PRs; the label route is the one I follow.

alexey-milovidov added a commit to niyue/ClickHouse that referenced this pull request Aug 20, 2026
…from master

Master merged ClickHouse#110648, which reworked how a mutation recalculates
`MATERIALIZED` columns: chains are followed transitively for `UPDATE`
and for `APPLY PATCHES`, a column reset by `CLEAR COLUMN` enters
dependency analysis so a `DELETE WHERE` TTL that reads it is
recalculated, and every `MATERIALIZED` expression is re-evaluated when
a clear makes any of them stale. The master merge in this branch kept
this file's own version, so all of that was lost and the master test
`04546_ttl_delete_where_recalc_after_update` started failing.

Bring the behaviour back on top of the matcher-aware version of the file:

- Collect every `MATERIALIZED` column's required source columns in
  `materialized_column_dependencies` and extend
  `column_to_affected_materialized` to the transitive closure, so
  `m2 MATERIALIZED m1 MATERIALIZED src` recomputes `m2` as well.
- Replace the two ad-hoc leveled emitters with a single
  `emit_materialized_recompute_stages`, and use it for `UPDATE` and for
  the `MATERIALIZED` columns an old-shape patch part does not carry.
- Seed the closure and the cleared columns into dependency analysis, and
  add the closure to the skip-index, projection and statistics rebuild
  predicates. The blanket `TTL_TARGET` fallback added earlier is dropped:
  `StorageInMemoryMetadata::getColumnDependencies` now walks
  `where_expression_columns`, which is the mechanism it stood in for.
- A `CLEAR COLUMN` that makes any `MATERIALIZED` column stale again
  re-evaluates every `MATERIALIZED` expression, except the ones that
  cannot be recomputed safely (an `EPHEMERAL` input) or must not be
  rewritten in place (a sorting or partition key input). The rejection
  guards stay scoped to the stale closure.
- The cleared column is pinned to its type default in the readonly stage
  only when something recomputed actually reads it. Otherwise TTL has to
  see the column's own `DEFAULT` expression instead.

`04837_clear_column_rematerializes_only_dependents` is adapted to the
restored semantics and gains a case for a `MATERIALIZED` sorting key
column outside the closure, which keeps its stored value.
alexey-milovidov added a commit that referenced this pull request Sep 2, 2026
…hemeral-materialized

Master has independently landed the same design this pull request proposed:
`clear_affected_materialized` is now the dependency closure of the cleared
columns (`affected_materialized_closure(clear_column_names)`) instead of every
`MATERIALIZED` column in the table, and master adapted
`04546_ttl_delete_where_recalc_after_update` and
`04648_mutation_statistics_type_mismatch` to the narrow semantics rather than
deleting the cases. Master's side is taken for all of that, so the branch no
longer carries a competing revert of #110648.

What remains unique to this pull request and is preserved:

- The stale-`MATERIALIZED` warning in `MutationsInterpreter::prepare` also fires
  for cleared columns, not only updated ones: a `MATERIALIZED` column reading an
  `EPHEMERAL` column is skipped by the recompute, so a `CLEAR COLUMN` of one of
  its regular dependencies silently leaves the on-disk value stale.
- The regression test for the original bug, renumbered
  `04926_clear_column_ephemeral_materialized` -> `05055_...` because master took
  the 04926 prefix.
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.

TTL DELETE WHERE is silently never applied after a mutation changes the WHERE-referenced column

6 participants