Repository navigation
Recompute MATERIALIZED columns when a column TTL resets their source - #117815
alexey-milovidov merged 12 commits into
Conversation
When a column TTL expires, the merge resets the source column to its default but left the `MATERIALIZED` columns computed from it untouched, so they kept the value derived from the pre-expiry data forever - no later merge repairs it, and the column contradicts its own expression. `ALTER TABLE ... CLEAR COLUMN`, the other path that resets a column to its default, already recomputes dependent `MATERIALIZED` columns. `TTLTransform` now recomputes, after the TTL algorithms have run, the `MATERIALIZED` columns whose expression reads a column with a TTL. The expressions are evaluated on the post-TTL block, so a row that did not expire keeps its value. Left alone are a dependent that is not deterministic (recomputing would also change the rows the TTL did not touch), one that has a TTL of its own (the TTL has just reset it), and one that takes part in the sorting, primary or partition key (recomputing would invalidate the order of the part being written). The mutation pipeline of `ALTER TABLE ... MATERIALIZE TTL` reads only the columns it rewrites, so a dependent that is not in its block is recomputed by the next merge instead. Closes: #117310
|
Workflow [PR], commit [36f6762] Summary: ✅
AI ReviewSummaryThis PR fixes the stale Missing context / blind spots
Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 36f6762.
Changed lines: Changed C/C++ lines covered: 146/153 (95.42%) · Uncovered code |
|
One more leg, not covered by the inline review: a dependent whose expression is not total on the source column's default turns a previously working table into one whose TTL merge always fails. The recompute at CREATE TABLE tb (d DateTime, x Int32 TTL d + INTERVAL 1 SECOND, mk Int32 MATERIALIZED intDiv(100, x))
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO tb (d, x) VALUES (now() - 3600, 41); -- mk = 2, fine
OPTIMIZE TABLE tb FINAL;Verified on this PR's CI binary (26.9.1.1, head 39dbc94, A contained fallback would preserve the fix without the regression: catch the exception per dependent, keep the stored (stale) column for that block, and log a warning — the same stale-tolerant treatment the PR already gives its disclosed exclusions. On the chain case the inline review already flags ( |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes6 object files changed (+64.57 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units10 translation units recompiled, 65 s compile time in total, 10 of them have a recent master baseline. |
…ency order The recomputation `TTLTransform` gained selected only the columns whose own expression reads a column a TTL resets, reanalysed the raw default AST to find them, and ran after every algorithm had finished. Three consequences, all reported on the pull request: - A chain was left half repaired. With `m1 MATERIALIZED x + 1, m2 MATERIALIZED m1 + 1`, `m1` was recomputed and `m2` was not, so `m2` no longer even matched its own stored input - before, the two at least agreed with each other. - A dependent reading the expired column through an `ALIAS`, or reading a subcolumn of it, never matched: the analysis was keyed on the raw carriers, so `reset_columns` held `x` and `t` while the required columns were `a` and `t.a`. - Every column that has a TTL of its own was skipped table-wide, although only the rows whose own TTL was due had been reset. Which value such a column ended up with also depended on the order `getColumnTTLs` happened to return, because that decided whether its algorithm ran before or after the one that resets the column it reads. The analysis is `MaterializedColumnDependencies` now - the graph `UPDATE`, `CLEAR COLUMN`, `APPLY PATCHES` and `AlterConversions` already share, which expands `ALIAS` references, reports a dependency on a subcolumn as one on the whole column, and leaves out a column reading an `EPHEMERAL` one, which no part holds. `findColumnsToRecalculate` closes the set transitively. The dependents are grouped into levels, a column of level `i` reading only columns of the lower levels, and the recomputation is interleaved with the column TTL algorithms: the TTL of a column nothing recomputes runs first, then the levels in order, and the own TTL of a dependent runs right after the level that recomputed it, so its reset wins row by row over the recomputed value. `TTLAggregationAlgorithm` emits the last group it accumulated from `generate`, after the last block was consumed, and the column TTL algorithms reset their columns in that block too, so `consume` and `generate` go through the same `executeAlgorithms`. Left alone are a dependent that is not deterministic, one that is already expired for the whole part, and one that takes part in the sorting, primary or partition key. Nothing changes such a column, so the dependents reading it keep the value they already have and stay consistent with it.
…LIZE TTL` For a table whose only TTL is a column TTL, the mutation read the TTL targets and the columns the TTL expressions need, so a `MATERIALIZED` column computed from an expiring column was not in the block and `TTLTransform` could not rewrite it. Leaving it to the next merge is not enough: this is the command that applies a column TTL to a part no merge is going to touch, and once it has run the part records the TTL as applied, so on a single-part table the stale value stayed there for good. The transitive closure comes from the same `MaterializedColumnDependencies` the rest of the file uses, restricted to the columns the part holds, and enters `dependencies` as `TTL_TARGET`, which is what makes the mutation read and write them.
…`05073` One case per leg the review asked for, each of which the pull request's earlier head got wrong: - A three-hop chain: `0 1 2 3`, where it used to give `0 42 43 44`. - A dependent with a TTL of its own that is not due for the row whose source expired: `0 1`, where it used to give `0 42`. - A dependent reading the expired column through an `ALIAS` and one reading a subcolumn of an expiring `Tuple`: `101` and `1`, where they used to give `142` and `8`. - A `GROUP BY` TTL whose last group is emitted at the end of the part rather than from a consumed block: `m = 1`, where it used to give `43`. That case has to use a column TTL that is only partially due, because a `GROUP BY` TTL next to a column TTL expired for the whole part throws `NOT_FOUND_COLUMN_IN_BLOCK` before any of this runs, with no `MATERIALIZED` column involved - a separate bug. - A `MATERIALIZED` expression that is not defined on the default of the column it reads (`intDiv(100, x)`), which has no correct value after the expiry: the merge reports `ILLEGAL_DIVISION` rather than writing a value that contradicts the expression. The same schema already rejects an `INSERT` of `x = 0` and fails `ALTER TABLE ... CLEAR COLUMN x` the same way.
|
🕵 @zlareb1 thank you - both legs you raised are handled, one by fixing it and one by keeping it and saying so out loud. The chain. You are right that it was worse than " The expression that is not total on the default. Kept as it is, deliberately, and
So the choice is between reporting a schema whose Two more things came out of this round:
CREATE TABLE t (k Int32, d DateTime, x Int32 TTL d + INTERVAL 1 SECOND) ENGINE = MergeTree ORDER BY k
TTL d + INTERVAL 1 DAY GROUP BY k SET x = max(x);
INSERT INTO t VALUES (1, '2000-01-01 00:00:00', 41), (1, '2000-01-02 00:00:00', 42);
OPTIMIZE TABLE t FINAL;
-- Code: 10. DB::Exception: Not found column x in block. There are only columns: k, d. (NOT_FOUND_COLUMN_IN_BLOCK)
|
|
🕵 Correction to the repro I posted for the pre-existing CREATE TABLE t (k Int32, d DateTime, x Int32 TTL d + INTERVAL 1 SECOND)
ENGINE = MergeTree ORDER BY k
TTL d + INTERVAL 1 DAY GROUP BY k SET x = max(x)
SETTINGS min_bytes_for_wide_part = 0;
INSERT INTO t VALUES (1, '2000-01-01 00:00:00', 41), (1, '2000-01-02 00:00:00', 42);
OPTIMIZE TABLE t FINAL;
-- Code: 10. DB::Exception: Not found column x in block. There are only columns: k, d. (NOT_FOUND_COLUMN_IN_BLOCK)Checked on this pull request's own CI binary (26.9.1.1, |
…IALIZE TTL` `ALTER TABLE ... MATERIALIZE TTL` asked for the dependent `MATERIALIZED` columns of an expired column, but not for the columns their expressions read next to it, and not through the closure the skip index, projection and statistics rebuild is keyed on. So `m MATERIALIZED x + y` with a TTL on `x` alone had no `y` in the block, `TTLTransform` skipped `m`, and the command rewrote it with the stale value - exactly what it is meant to repair. And a projection grouping by a column no TTL touches was rebuilt without that column in the block: `calculateProjection` fills a missing required column with a type default, so the projection answered with a group key the base table does not have. The dependents now enter `new_updated_columns` before that closure is taken, and every column their expressions read is asked for as a read-only dependency. The rebuild decision itself was already covered: it keys on `changed_columns`, which the dependents joined as `TTL_TARGET`. What was missing were the columns read next to them.
|
🕵 A separate defect found while covering this, on the branch as it stands ( CREATE TABLE t (d DateTime, x Int32, m Int32 MATERIALIZED x + 1, INDEX i m * 2 TYPE minmax GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple()
SETTINGS min_bytes_for_wide_part = 0, materialize_ttl_recalculate_only = 0;
INSERT INTO t (d, x) VALUES ('2000-01-01 00:00:00', 41);
SET materialize_ttl_after_modify = 0;
ALTER TABLE t MODIFY COLUMN x Int32 TTL d + INTERVAL 1 SECOND SETTINGS mutations_sync = 2;
ALTER TABLE t MATERIALIZE TTL SETTINGS mutations_sync = 2;
SELECT x, m, m * 2 FROM t; -- 0 1 2, so the data is right
SELECT count() FROM t WHERE m * 2 = 2 SETTINGS use_skip_indexes = 0; -- 1
SELECT count() FROM t WHERE m * 2 = 2; -- 0 <-- the index prunes it
What discriminates, all on the same binary:
So it needs all three of: the mutation path, a non-trivial index expression, and a column that Verified on the branch with the fix reverted, so it comes from
|
…ot before
The mutation pipeline evaluated the skip index expressions into the block before the TTL transform,
and the writer reuses whatever expression column it finds there rather than evaluating it itself. So
once `MATERIALIZE TTL` started recomputing the `MATERIALIZED` columns of an expired column, an index
over one of them was written from the pre-expiry value while the part stored the new one, and the
index then pruned granules that do match:
```sql
CREATE TABLE t (d DateTime, x Int32, m Int32 MATERIALIZED x + 1, INDEX i m * 2 TYPE minmax GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple() SETTINGS min_bytes_for_wide_part = 0, materialize_ttl_recalculate_only = 0;
INSERT INTO t (d, x) VALUES ('2000-01-01 00:00:00', 41);
SET materialize_ttl_after_modify = 0;
ALTER TABLE t MODIFY COLUMN x Int32 TTL d + INTERVAL 1 SECOND SETTINGS mutations_sync = 2;
ALTER TABLE t MATERIALIZE TTL SETTINGS mutations_sync = 2;
SELECT x, m FROM t; -- 0, 1
SELECT count() FROM t WHERE m * 2 = 2 SETTINGS use_skip_indexes = 0; -- 1
SELECT count() FROM t WHERE m * 2 = 2 SETTINGS use_skip_indexes = 1; -- 0, the index says [84, 84]
```
Both mutation paths did it. The one that rewrites every column materialized
`getPrimaryKeyAndSkipIndicesExpression` ahead of the TTL transform, so that block is moved after it.
The one that rewrites some of them appends its expressions where it decides which indices to
recalculate, which is before the task builds the rest of the pipeline, so the expression list is
carried on the context and materialized after the TTL instead.
The merge pipeline was never affected: it has no such precomputation, and its writer evaluates the
index expressions on the block the TTL has already worked on.
…zed-columns-after-column-ttl-117310
…zed-columns-after-column-ttl-117310
|
🕵 Merged Following the AI review's metadata finding, the changelog category is now |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…zed-columns-after-column-ttl-117310 # Conflicts: # src/Storages/MergeTree/MutateTask.cpp
…ATERIALIZE TTL` A review asked whether the some-columns `MATERIALIZE TTL` path rebuilds the statistics of the `MATERIALIZED` columns recomputed after a column TTL. It does: the recomputed columns enter as `TTL_TARGET` dependencies, which are not read-only, so they land in `changed_columns` and the loop at the end of `MutationsInterpreter::prepare` puts them into `materialized_statistics`. Pin that with a test on a wide part that is mutated through `MutateSomePartColumnsTask`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The leaked merge is retried without end on both the old and the upgraded server because of issue ClickHouse#123953: the recompute of a MATERIALIZED column added by ClickHouse#117815 throws inside every background TTL merge. The entry does not fix that issue and only matches this fixture's string. Co-Authored-By: Claude Opus 5.5 <[email protected]>
When a column TTL expires, the merge resets the source column to its default but left the
MATERIALIZEDcolumns computed from it untouched, so they kept the value derived from the pre-expiry data forever - no later merge repairs it, and the column contradicts its own expression:ALTER TABLE ... CLEAR COLUMN, the other path that resets a column to its default, already recomputes dependentMATERIALIZEDcolumns.TTLTransformnow recomputes them overMaterializedColumnDependencies- the same dependency graphUPDATE,CLEAR COLUMN,APPLY PATCHESandAlterConversionsuse, which expandsALIASreferences, reports a dependency on a subcolumn as one on the whole column, and leaves out a column that reads anEPHEMERALone, which no part holds. The set is closed transitively, because a dependent may read another dependent (m2 MATERIALIZED m1 + 1) and has to see its recomputed value, and the recomputation is interleaved with the column TTL algorithms: the TTL of a column nothing recomputes runs first, then the dependents level by level, and the own TTL of a dependent runs right after the level that recomputed it, so its reset wins row by row over the recomputed value.TTLAggregationAlgorithmflushes the rows of aGROUP BYTTL at the end of the part, after the last block was consumed, so both entrypoints go through the same step.Left alone are a dependent that is not deterministic (recomputing would also change the rows the TTL did not touch), one that is already expired for the whole part (recomputing would undo the expiry), and one that takes part in the sorting, primary or partition key (recomputing would invalidate the order of the part being written). Nothing changes such a column, so the dependents reading it keep the value they already have and stay consistent with it.
ALTER TABLE ... MATERIALIZE TTLreads and writes the dependents as well now. It is the command that applies a column TTL to a part no merge is going to touch, and it used to read only the TTL targets and the TTL expressions, so on a single-part table the dependents stayed stale indefinitely. The read set covers the columns a dependent's expression reads next to the expired one (yofm MATERIALIZED x + y), and the dependents take part in the closure the skip index, projection and statistics rebuild is keyed on, so an artifact over a recomputed column is rebuilt and the columns it reads are in the block rather than filled with a type default.Rebuilding those artifacts also had to move. The mutation pipeline evaluated the skip index expressions into the block before the TTL transform, and the writer reuses whatever expression column it finds there, so an index over a recomputed column was written from the pre-expiry value and then pruned granules that do match -
INDEX i m * 2 TYPE minmaxoverm MATERIALIZED x + 1answered0where a scan answers1. Both mutation paths materialize their index expressions after the TTL now. The merge pipeline never had the precomputation and was not affected.A
MATERIALIZEDexpression that is not defined on the default of a column it reads has no correct value once the TTL resets that column, and the error propagates: the merge fails rather than writing a value that contradicts the expression.mk MATERIALIZED intDiv(100, x)next tox TTL ...is such a schema, and it is already one that rejects anINSERTofx = 0and whoseALTER TABLE ... CLEAR COLUMN xfails the same way, leaving the mutation in the queue. This is a behaviour change for a table whose TTL merge succeeds today with a stale value, and the test pins it.Closes: #117310
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
A
MATERIALIZEDcolumn computed from a column with a TTL is now recomputed when the TTL resets that column, both during a merge and inALTER TABLE ... MATERIALIZE TTL. Previously it kept the value computed before the expiry forever. If the dependent expression is not defined on the expired column's default (for exampleintDiv(100, x)whenxexpires to0), the TTL merge now throws instead of writing the stale pre-expiry value; make the expression total on the default (intDivOrZero,if(x = 0, ...)) if such an existing table must keep merging. This fixes #117310.Workflow [PR]
Sync PR [sync-upstream/pr/117815]
Version info
26.10.1.1228-master(included in26.10and later)