Repository navigation
Recalculate TTL when a mutation updates a DELETE WHERE column - #110648
alexey-milovidov merged 13 commits into
Conversation
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
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260716-070600 |
|
cc @CurtizJ @Michicosun — could you review this? It fixes a |
|
Workflow [PR], commit [913d565] Summary: ✅
AI ReviewSummaryThis PR correctly fixes the original Findings❌ Blockers
Final VerdictChanges requested. |
…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]>
|
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]>
CI finish ledger — 2b95d52Every failure below has an owner. Neither is caused by this PR's diff (TTL/MATERIALIZED recompute in
Session id: cron:our-pr-ci-monitor:20260716-193000 |
CI finish ledger — 2b95d52Every 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
Session id: cron:our-pr-ci-monitor:20260716-203000 |
CI finish ledger — 3d9245dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The The integration cascade is a trunk defect in the 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.
|
Fixing PR for the Root cause: #109339 added a 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 No action is needed on this PR: its diff never touched PostgreSQL replication and did not cause this line. |
CI finish ledger - 738dc18Every 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
This PR's diff on this head is test-only ( Session id: cron:our-pr-ci-monitor:20260729-170000 |
CI finish ledger — 738dc18Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260729-164745 |
…e-mutation-recalc # Conflicts: # src/Interpreters/MutationsInterpreter.cpp
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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 140/142 (98.59%) · Uncovered code |
CI finish ledger - 913d565Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task No failures on this head. 174 check-runs, all completed: 156 success, 18 skipped, 0 failure. The one row from my previous ledger is resolved rather than re-listed: No Session id: cron:our-pr-ci-monitor:20260731-003000 |
CI finish ledger - 913d565CI is fully finished on this head and there are no failing checks.
Session id: cron:our-pr-ci-monitor:20260809-013000 |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The fix is quite complex, but I glad that it exists.
ReproducerCREATE 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:
Backport the fix to CC component owner: @Michicosun @CurtizJ Analysis metadata
Introducing change: not identified
|
|
Confirmed the backport candidacy independently, with one correction and one prerequisite. Affectedness. I ran your reproducer verbatim against the official per-release binaries (
Your four branches are right and excluding 25.8 is right. The master arm closes the gap you flagged: that nightly's Label. One label is enough, and it is 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.
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 So the request is: label #112009 with Conflict counts in I am not authoring release-branch PRs; the label route is the one I follow. |
…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.
…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.
Changelog category (leave one):
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 anALTER TABLE ... UPDATEon a column referenced in theWHERE. 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 anALTER TABLE ... UPDATEmutation. The per-row drop decision is stored per part inrows_where_ttl_info, andStorageInMemoryMetadata::getColumnDependenciesonly tracked the columns of the TTL time expression (expression_columns), not the columns of theWHEREcondition (where_expression_columns). So updating aWHERE-referenced column produced noTTL_EXPRESSIONdependency,MutationsInterpreterskipped TTL recalculation, and the mutated part kept its pre-mutation (empty)rows_where_ttl_info. The rows were expired and matchedWHEREbut were never removed, not even byOPTIMIZE TABLE ... FINAL, until an explicitMATERIALIZE 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_columnsto the mutation dependency set, so anALTER UPDATEtouching them triggers a TTL recalculation. Removes the stale//TODO what about rows_where_ttl and group_by_ttl ??.On the
group_by_ttlhalf 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 beUPDATEd (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 andOPTIMIZE FINAL; with the fix the 2 flagged expired rows are deleted immediately.Version info
26.8.1.1545(included in26.8and later)