Repository navigation
Fix stale MATERIALIZED column values read through a chain while a mutation is pending - #114561
Conversation
…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 #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 #50237. The walk still excludes a MATERIALIZED column that reads an EPHEMERAL column, which is what #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: #100613 Closes: #50237 Co-Authored-By: Claude Opus 5 <[email protected]>
|
Workflow [PR], commit [7a5a547] Summary: ✅
AI ReviewSummaryThis PR centralizes Findings
Final VerdictLLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 160/165 (96.97%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Object file sizes13 object files changed (+87.54 KiB total), 1 added.
737 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 units373 translation units recompiled, 3417 s compile time in total, 372 of them have a recent master baseline. |
A `TTL` expression reading a transitively recalculated `MATERIALIZED` column was the one derived artifact left unverified. It is affected the same way a projection and a skip index are, and the symptom is worse: the expired rows are silently retained. Measured with the same test on both binaries. On `master` `d` stays at its `INSERT`-time `2102-02-21` while `m1` is recalculated, nothing expires, and `count()` is `100`. With the fix `d` becomes `2020-01-02`, every row is expired, and `count()` is `0`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three defects found in review of the transitive `MATERIALIZED` recalculation. The per-level stages were created with `stages.emplace_back(context)`, leaving `Stage::mutation_version` unset even though they belong to the same `UPDATE` command. On-fly reads derive the patch-visibility window from consecutive stages' versions, so an absent version left it unbounded above and a later patch became visible to the level stages, which then recomputed the dependent column from the patched data and overrode the value the patch itself carries. Measured: with a pending `UPDATE x = 20` and a lightweight `UPDATE ... SET z = 500`, the on-fly read gave `m1 = 520` while the materialized part plus its patch reads `510`. `AlterConversions::addColumnsRequiredForMaterialized` analysed the same default expressions without `replaceSubcolumnsToGetSubcolumnFunctionInQuery`. For `m1 MATERIALIZED t.a + 1` the dependency read as `t.a` while the pending command updates `t`, so the command was filtered out of the on-fly chain and the stale stored value was returned unless the query happened to also select `t`. Measured: `SELECT t, m1` gave `(20,0) 21` while `SELECT y, m1` gave `1 11`. This half is reproducible on `master` for a direct dependency, so it is not a regression of this change, but it is in the walk this change introduced. `CLEAR COLUMN` recomputed every `MATERIALIZED` column in a single stage, so each expression saw pre-stage values and a transitively dependent column stayed one step behind — the same defect this change fixes for `UPDATE`, on the sibling command. Its comment claimed transitive dependencies were covered; they were not. Measured: `CLEAR COLUMN x` on the chain `x -> m1 -> m2 -> m3` gave `0 1 12 13` instead of `0 1 2 3`. It now reuses `getAffectedMaterializedByLevel`, which also replaces a duplicate `TreeRewriter` scan over every default expression and, as a side effect, stops reaching columns blocked by an `EPHEMERAL` dependency. Each clause was verified in isolation: reverting only the version propagation turns only the patch-part case red, only the subcolumn rewrite turns only the subcolumn case red, and collapsing the levels back into one stage turns only the `CLEAR COLUMN` case red. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rialized-mutation # Conflicts: # src/Interpreters/MutationsInterpreter.cpp
`AlterConversions::addColumnsRequiredForMaterialized` only looked at the direct dependencies of the MATERIALIZED columns being read, so a column that reaches an updated column through another MATERIALIZED column (`m2 MATERIALIZED m1`, `m1 MATERIALIZED x`, `UPDATE x`) did not pull the intermediate column into the read set. `filterMutationCommands` then dropped the command that feeds the chain and `SELECT m2` returned the stale on-disk value while the mutation was still pending, even though selecting the whole chain returned the recomputed one. Walk the dependency graph transitively and add every intermediate MATERIALIZED column that reaches an updated column. Two details this needs: - the default expression is normalized with `replaceSubcolumnsToGetSubcolumnFunctionInQuery` before analysis, as `MutationsInterpreter::prepare` does, so `m MATERIALIZED t.a` is seen to depend on `t` rather than on `t.a`; - a MATERIALIZED column reading an EPHEMERAL one is never recalculated outside INSERT, so it is excluded instead of being analysed against physical columns, where the EPHEMERAL name does not resolve. The staging side of this (one recompute stage per dependency level) is already in master, so this pull request only covers the on-fly read path. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…by another replica Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ale value The test only exercised the input class where the narrow read set makes the query return a stale value. Three further classes reach the same defect through different paths, and two of them make the query fail instead: - selecting the updated column next to the deepest one keeps the command in the chain while the read set still lacks the intermediate hop, so the interpreter analyses the default of `m2` against a column list without `m1` and throws `Missing columns: 'm1' while processing: 'm1 + 1'`; - a single command assigning two columns is narrowed to the assignments the query reads, so `x = 20` is physically dropped from the rebuilt AST while the command survives on the other assignment; - a pending `DELETE` keeps a command alive with an empty updated-column set, which skips the analysis entirely and yields the stale value again. Verified on the pull request head: the full test matches the reference. On master it stops with `Code: 47` at the first added query. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… a flag The declaration promised to add "source columns of expressions of MATERIALIZED columns", which overstates what the function does: a dependency is added only when an updated column is reachable through it. Corrected, and the contract is now stated where the function is defined — why the read set has to be closed over those columns at all (it gates which commands survive `filterMutationCommands` and which columns the interpreter can resolve expressions against), followed by the three rules the walk obeys. The comments inside the function shrink accordingly: what the walk does and why belongs to the contract, while the three local comments keep only the part that is not recoverable from the code — the `getAllPhysical` omission, the rewrite that has to match `MutationsInterpreter::prepare`, and the EPHEMERAL policy. Two lookups also stop copying: - `is_materialized` used `getDefault`, which returns `std::optional<ColumnDefault>` by value, and `ColumnDefault`'s copy assignment deep-copies the expression. So a whole default expression AST was cloned per call just to read `kind`, and the lambda is called once per queue pop plus once per `can_recalculate`. It now reads through `tryGet`, which returns a pointer over the same `columns.get<1>()` lookup. `tryGet` rather than `get`, because the read set also holds virtual columns that `ColumnsDescription` does not know about. The explicit `expression` check reproduces `getDefault` returning nothing when the expression is null, which `get_dependencies` relies on. - `get_dependencies` cloned the expression that `getDefault` had already cloned. It now clones from the metadata reference directly, so the clone is the one that is actually needed: both calls that follow rewrite the AST in place and the expression belongs to the shared metadata snapshot. No behaviour change. `04869_materialized_chain_on_fly_read` matches the reference. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…level `reachesUpdatedColumn` answered the same question repeatedly. Walking a chain `m3 -> m2 -> m1 -> x`, the reachability of `m1` is established while answering for `m2`, and then established again when the queue reaches `m2` and asks about `m1` directly, so a chain of length n costs O(n^2) node visits where O(n) is enough. `dependencies_of` hid the expensive half of that — no expression is analysed twice — but the traversal itself was still quadratic. It also took `visited` by value and passed it by value into every recursive call, so each level deep-copied a set of column names. Passing it by value was not buying anything either: reachability is a property of a node, not of the path that reaches it, so a node already explored under one branch cannot answer differently under another, and re-exploring it is pure waste. Both go away by memoising the answer per column, which subsumes the visited set: the entry inserted before recursing is the cycle breaker. On an acyclic graph an entry is only read once its value is final, because a column still being visited is reachable exclusively from its own subtree, and `MutationsInterpreter` rejects a cyclic MATERIALIZED dependency outright. Written as a self-recursive lambda over a memo map, which is how `MutationsInterpreter::prepare` already walks the same graph in `getAffectedMaterializedByLevel`. No behaviour change. `04869_materialized_chain_on_fly_read` matches the reference, and the EPHEMERAL and multiple-assignment probes are byte-identical to the previous build. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… interface `queue` said nothing beyond the container, and `read_columns_set` right above it already shows the convention this function follows: a suffix earns its place by disambiguating two variables holding the same content, not by restating the declared type. The worklist is also not a queue of read columns — it is seeded from the read set, but the dependencies discovered along the way are pushed onto it too, so after the first iteration it holds a mix. What it does hold, at every point, is the columns whose dependencies have not been examined yet. `std::queue` rather than `std::deque`, since the default underlying container is `std::deque` anyway and nothing here needs more than front/push/pop. The iterator-pair constructor it is built with is C++23, which the bundled libc++ provides. Pure rename and interface narrowing. `04869_materialized_chain_on_fly_read` matches the reference, and the read-set and EPHEMERAL probes are byte-identical to the previous build. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The two things the loop decides — whether a dependency has to be read, and whether it has been recorded already — were entangled in one condition, with the `insert` doubling as the second test through its `second`. Reading it required noticing that the insert only runs when `needed` holds, which is what keeps an unneeded dependency out of the set. Hoisting the "already required" test next to the EPHEMERAL one puts both reasons to skip a dependency in the same place, leaves the body saying plainly that a needed dependency is recorded and queued, and stops evaluating the reachability question for a dependency reached a second time through another column. That question is memoised, so the saving is a few hash lookups per repeated edge rather than a walk, but the entangled condition was paying them for nothing. Equivalent by cases: an already-recorded dependency was and is ignored, a new needed one is recorded and queued, a new unneeded one is left alone. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…nd set `required_source_columns` accumulated what the walk found and a loop at the end merged it into the read set, which meant three things were tracked where one would do: the set of columns to add, the set already added, and — implicitly, by being absent from both — the columns the query asked for. A dependency that was already a read column was therefore recorded and queued anyway, only for the merging loop to discard it, so it cost a redundant visit of its own dependencies. Inserting into `read_columns` and `read_columns_set` directly collapses all of that: `read_columns_set` is the one thing to test against, and it answers both questions at once, because a column is in it exactly when it is either one the query asked for or one an earlier step already added. The merging loop goes away. Nothing iterates `read_columns_set` while the walk runs — the worklist was constructed from it up front — so mutating it in place is safe. The columns appended to `read_columns` now come out in the order the walk finds them rather than in the iteration order of an intermediate `NameSet`, which is `std::unordered_set`, so no caller could have been relying on the previous order. `04869_materialized_chain_on_fly_read` matches the reference, the read-set probes are byte-identical to the previous build, and reading columns that depend on each other (`SELECT m1, m2`, `SELECT m3, m1`) still recomputes the whole chain. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ng out `updated(d) || (can_recalculate(d) && reaches(d))` appeared twice: once in the loop deciding whether to read a dependency, once inside the reachability walk deciding whether to keep descending. They are the same question asked at different depths — a column matters when it is updated itself or leads to one — so the recursion collapses into `any_of(dependencies, needs_reading)` and the loop into a single call. Equivalent by construction: `needs_reading(c)` unfolds to exactly the disjunction the two sites spelled out, and the memo still holds only recalculable columns that are not updated themselves, because the two cheap tests come first. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… read
Closing the read set over a chain made every pending command survive filtering far
more often than before, and that exposed a second use of `available_columns` in
`MutationsInterpreter::prepare`: the list a MATERIALIZED default expression is
resolved against. A column the mutation does not affect still gets analysed there,
and its dependencies are legitimately outside the read set, so the analysis failed
with `UNKNOWN_IDENTIFIER` and took the query with it. On a table carrying one
unrelated MATERIALIZED column, an ordinary read turned from a stale answer into an
error:
CREATE TABLE t (x Int32, y Int32, m Int32 MATERIALIZED x + 1, n Int32 MATERIALIZED y + 1) ...
ALTER TABLE t UPDATE x = 20 WHERE 1; -- pending
SELECT m, n FROM t; -- Missing columns: 'y' while processing: 'y + 1'
Deciding whether a column has to be recalculated must not require reading what it
reads, so the analysis now resolves against every column of the table. For a
materialising mutation this changes nothing, since `available_columns` already
covers the part; only an on-fly read has a narrow list.
The read set has to give a bit in the other direction. A column that IS
recalculated needs its whole expression readable, not only the part that leads to
an updated column: `c MATERIALIZED m1 + y` reads `y` next to the recalculated
`m1`, and `y` was left out because nothing updates it. So the walk now asks
whether the column it visits is recalculated, and if so takes all of its
dependencies, rather than asking of each dependency whether it leads anywhere. A
column that keeps its stored value contributes nothing, which also stops pulling
in the updated dependency of a MATERIALIZED column blocked by an EPHEMERAL one.
The two together also settle the pre-existing case of reading an updated column
next to any MATERIALIZED column whose dependencies are not selected, which failed
the same way on master:
SELECT x, n FROM t; -- was Missing columns: 'y', now 20 6
Covered by a new `on the fly, unaffected columns` case. Measured against master
`5bd006cd298` and against this branch before the fix: master returns the stale
value for the unaffected-chain reads and throws for the ones that select the
updated column, and the branch before the fix throws for both.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…s one question `needs_reading` was answering two questions at once and the caller had to patch it back. It accepted a column a command writes whatever its kind, because that is the base case of the descent, and the loop then had to reject exactly that case with an extra `can_recalculate`, since a plain column has no expression to ask for dependencies of. Two tests of the same thing, in an order that mattered and only on the one population where the two disagree — a written plain column. Reordering the two early returns inside was a silent regression to stale values, and dropping the one in the loop aborted on a null AST. The base case belongs to the edge, not to the node: what the descent needs to know is whether a *dependency* changes, and the natural place to ask is where the dependencies are enumerated. Moved there, `can_recalculate` becomes the first thing the predicate does, the predicate means exactly one thing — the interpreter recalculates this column — and it implies its own precondition, so the loop needs no conjunction. Renamed to match. Both branches now share the one memo write, which is the point: writing them as two returns is how the memo entry gets left at its provisional `false` while the function returns `true`, and a later question about the same column then reads the poisoned entry. Measured on a chain of three, that turns `SELECT m3` back into the stale value, order-dependently, with no error. `04869_materialized_chain_on_fly_read` matches the reference, the read-set and EPHEMERAL probes are byte-identical to the previous build, and both orders of `SELECT m1, m3` — the ones that would read a poisoned memo entry — recompute the chain. Also restores what the comment on `can_recalculate` used to say about EPHEMERAL columns; it had been generalised away, leaving the test on the dependencies of the expression unexplained. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Both comments buried what a reader actually needs in a subordinate clause, and one of them described the caller's use rather than the predicate's meaning. `can_recalculate`: that the EPHEMERAL test looks at what the expression reads and not at the column itself is the thing that surprises, so it is now a sentence of its own instead of a trailing aside, and "such a column" is gone — it could have meant either of the two columns in the preceding sentence. `is_recalculated`: dropped "so the read set owes its whole expression", which belongs to the loop that calls it and is stated there, and dropped "at all" from "can be recalculated", which the name already says. In their place, the reason the written case is tested in the loop rather than by recursing: a written column is usually a plain one and would fail `can_recalculate`, so recursing into it would lose the base case. That constraint was previously visible only as a half-clause between dashes, which reads as a remark rather than as the invariant it is. The paragraph about the memo now explains the mechanism instead of listing two properties side by side: a cycle terminates *because* it reads the entry while that entry is still provisional. Also drops the line above the dependency loop stating that none of the dependencies is EPHEMERAL. It was true, and true for every call since `can_recalculate` runs before the memo, but it is the third place saying so and it documents the absence of a guard, which invites the reader to wonder who removed one. Comments only. `04869_materialized_chain_on_fly_read` matches the reference. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…h from #115638 Avogar tried an alternative on top of this branch in #115638 and asked for it to be moved here. This is that change, applied verbatim: the four test files this branch already carried are byte-identical in it, and `Settings::apply_on_fly_for_read` is kept. What it adds over what was here: - `MaterializedColumnDependencies` — the dependency graph over a table's `MATERIALIZED` columns, built once and shared by the read path and `MutationsInterpreter` instead of being derived separately in each. `getAffected` closes over the graph, so a column reachable only through another recomputed one is included. - `filterMutationCommands` puts the columns a surviving command reads into the read set, and one of those can itself be a `MATERIALIZED` column of a chain (`DELETE WHERE m2 > 100`), which can in turn keep an older command alive. Closing the set and filtering now run in a loop until the set stops growing; it only grows and is bounded by the width of the table, so it terminates. - A command may name a subcolumn as written (`t.a`) while the read set is keyed on storage columns, which made every read of the table fail with `NO_SUCH_COLUMN_IN_TABLE`. Names now go through `getNameInStorage` on the way in. This one reproduces on master. - `getMutationSteps` and `getMutationActions` share one `buildMutationChainForRead` instead of each recomputing the read set and the command filter. Test `04926_on_fly_mutation_read_set_closure` covers the chain reached from a pending `DELETE` predicate, the subcolumn spelling, and the cases that must not move. Co-authored-by: avogar <[email protected]> Co-Authored-By: Claude Opus 5 <[email protected]>
A `MATERIALIZED` column may be defined over an `ALIAS` column, and until now that made every
mutation on the table throw, including one updating a column the expression never mentions:
CREATE TABLE t (x Int32, z Int32, a Int32 ALIAS x + 100, m Int32 MATERIALIZED a + 1)
ENGINE = MergeTree ORDER BY tuple();
ALTER TABLE t UPDATE z = 5 WHERE 1;
-- Code: 47. Missing columns: 'a' while processing: 'a + 1' ... (UNKNOWN_IDENTIFIER)
The column list the default is analysed against is the physical one, and an `ALIAS` is physical-
excluded. Merely adding aliases to it would let `TreeRewriter` resolve the name, but the expression
would then still read `a` at execution time and no part has a column `a`, so the recompute stage
would fail on it instead. The reference has to be replaced by the expression it stands for, which
`ReplaceAliasByExpressionMatcher` does — the same visitor `IndexDescription::initExpressionInfo`
uses so a skip index can reference an `ALIAS` column.
There is one place to do it now: `MaterializedColumnDependencies` hands the same expression to the
dependency analysis and to the recompute stage, so the expansion reaches both. It runs before the
subcolumn rewrite, so a subcolumn reached through an alias is normalised too.
Unlike the `EPHEMERAL` case next to it, nothing is lost: `m` recalculates correctly from the stored
`x`, and an `ALIAS` column is recomputed per query so it can never itself be stale.
Measured on a Debug build, before and after: without the change both `UPDATE z = 5` and
`UPDATE x = 20` throw `UNKNOWN_IDENTIFIER`; with it the first leaves `m` alone and the second gives
`x, a, m = 20, 120, 121`, on the settled part and on the on-fly read alike.
Co-Authored-By: Claude Opus 5 <[email protected]>
…e table up front
`MaterializedColumnDependencies` analysed every MATERIALIZED column of the table in its constructor,
and it is constructed per read task per part on the on-fly read path. A query touching one column of
a table with a hundred MATERIALIZED columns paid a `TreeRewriter` run for the ninety-nine it does not
read, once per part.
Measured on a Debug build, 300 parts, `SELECT sum(y)` with a pending `UPDATE x`, where `y` is read by
no MATERIALIZED column, best of five:
MATERIALIZED columns 0 10 50 100
up front 0.11s 0.15s 0.60s 1.90s
on demand 0.11s 0.11s 0.11s 0.11s
The cost is on the on-fly path and nowhere else: with 100 such columns the same query takes 0.09s with
no mutation pending, 0.09s with one pending and `apply_mutations_on_fly = 0`, and 1.9s with it on. It
also grows linearly with the number of parts — 0.24s at 25 parts, 1.89s at 300 — which is the per-read-
task construction.
So the graph now records only its nodes up front and rewrites and analyses an expression the first
time that column is asked about. The read-set closure asks per column through `willBeRecalculated`,
which walks upstream from the column it is given, instead of consuming a set that had to enumerate the
whole graph to exist. `getAffected` had exactly one caller and is replaced by it; the enumerated form
is easy to bring back if something needs it.
`willBeRecalculated` marks a column as not-recalculated while it is being answered, so a cycle in the
graph terminates rather than recursing — a cyclic set of defaults cannot be recomputed at all, which
is what the answer says.
`04869`, `04926`, `05023` and `05024` all pass unchanged.
Co-Authored-By: Claude Opus 5 <[email protected]>
…s key once Three things the previous commit left rough, no behaviour change: - The "already analysed" flag lived in a second `unordered_map` beside the graph, so every lookup hashed the column name twice and a miss inserted into it. It is gone: an entry is analysed when its `expression` is set, and the whole `Column` is assigned in one step at the end, so a throw part-way through leaves the entry untouched instead of half-filled. - `willBeRecalculated` compared the whole `changed_columns` set against the memoised one on every recursive step. The check belongs to entering the walk, so it moved to a public wrapper and the recursion is a private `willBeRecalculatedImpl` that takes the already-checked set. - The comment on writing the result back said the recursion "can rehash the map" as the reason not to reuse the iterator. Rehashing invalidates iterators but not references, so the wording was imprecise; it now says which of the two it means. Also corrected the note on the cycle guard: `CREATE TABLE` rejects cyclic defaults outright (`Code: 174 CYCLIC_ALIASES`, measured), so the guard is not reachable today. It is kept because it is the memo entry itself rather than a separate mechanism, and it makes the recursion total without depending on that check. `04869`, `04926`, `05023` and `05024` pass, and the benchmark is unchanged — flat at 0.11s for 0, 10, 50 and 100 MATERIALIZED columns over 300 parts. Co-Authored-By: Claude Opus 5 <[email protected]>
…the columns asked about
Two defects in the previous two commits, both found by review and both reproduced before fixing.
**The expansion dropped the alias's type.** `ReplaceAliasByExpressionMatcher` substitutes the raw
expression, while reading an `ALIAS` column applies the declared conversion, so a narrowing alias made
the recomputed value differ from the inserted one:
CREATE TABLE t (x UInt16, a UInt8 ALIAS x, m UInt16 MATERIALIZED a) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t (x) VALUES (300); -- x=300 a=44 m=44
ALTER TABLE t UPDATE x = 301 WHERE 1; -- x=301 a=45 m=301, measured; m must be 45
That turned an error into a wrong value, which is worse than the error it replaced. The expansion now
goes through `replaceAliasColumnsInQuery`, which is the path a read of an `ALIAS` column takes and
carries the type with it via `addTypeConversionToAST`. Measured after: `301 45 45`, settled and on the
fly alike; `05024` covers both.
**The recompute stage analysed every column before checking whether it needed it.** `tryGet` was called
for every column of the table ahead of the `affected_materialized` membership test, so a read that
recomputes even one MATERIALIZED column paid for all of them and the on-demand analysis bought nothing.
Both tests are over sets that are already built, so they go first. Same ordering in the `CLEAR COLUMN`
scan, against `available_columns_set`.
Measured, 300 parts, `SELECT sum(m1)` where every `m<i>` reads the updated `x`, best of five:
MATERIALIZED columns 1 10 50 100
analyse then filter 0.38s 0.44s 1.0s 2.4s
filter then analyse 0.38s 0.41s 0.51s 0.66s
The case where nothing is recomputed is unchanged — flat at 0.11s for 0, 10, 50 and 100 columns.
`04869`, `04926`, `05023`, `05024` and `01845_add_testcase_for_arrayElement` pass.
Co-Authored-By: Claude Opus 5 <[email protected]>
Its on-fly cases keep a mutation pending with SYSTEM STOP MERGES, which under shared catalog only stops the current replica — the other one can materialize the mutation and the case would pass without exercising the path it is there for. Same tag and wording as `04869`, `04926` and `05023`. Co-Authored-By: Claude Opus 5 <[email protected]>
|
@Avogar a few things worth mentioning:
|
No behaviour change — naming, structure and comments only. **The conditional accessor answered a different question than the caller asked.** It returned a bool, so `addColumnsRequiredForMaterialized` looked the column up twice — `willBeRecalculated` and then `tryGet` — and dereferenced the node without a null check, correct only because a true answer implies an analysed node. It now asks once: `findColumnsToRecalculate` returns the dependency list itself, empty for a column that keeps its stored value, and the BFS is a plain `for` over it. **The names described the mechanism rather than the result.** `tryGetNodeIfRecalculated` was a stack of prefixes, and `struct Column` did not say it was part of a graph. The node is now `MaterializedDependencyNode` and the plain accessor is `findNode`, the same pair `TablesDependencyGraph` uses. `find` for the nullable one, so the prefix says whether the caller has to check. **Two forwarding layers are gone.** `analyse` is `findNode` itself, and `willBeRecalculatedImpl` is `willBeRecalculated`; the memo's key check moved into `findColumnsToRecalculate`, which is the walk's only entry point, so it still runs once per walk rather than once per column visited. Comments cut to the ones that explain why the code is not simpler than it looks: the rewrite contract on `expression`, EPHEMERAL columns in the analysis set, the two rewrites and their order, the clone that keeps `expression` pristine, the single assignment that keeps a throw from leaving a half-filled entry, and the iterator the recursion can invalidate. Co-Authored-By: Claude Opus 5 <[email protected]>
The comment above the loop opened with "the two steps feed each other" and left the reader to work out which two, and it omitted the half that makes the feedback real: the filter admits a command only when it touches the read set. Name both calls and state the admission rule, so every clause maps to a line of the loop. Co-Authored-By: Claude Opus 5 <[email protected]>
`Closing the read set` was borrowed vocabulary — neither call says closure — and the sentence about termination restated the exit condition three lines below it and then added that the read set is bounded by the width of the table, which is not in doubt. Say what the two calls do in their own words, and drop the rest. `num_read_columns` counted nothing; it holds the size the read set had before the round, so `old_read_columns_size`. Co-Authored-By: Claude Opus 5 <[email protected]>
One conflict, in `AlterConversions.cpp`, from two master commits landing in the code this branch rewrites: - `36bb4f1b3d6` reverts #103182 (patch parts sort key). Resolved master's way: the `PatchParts/PatchPartsUtils.h` include goes, along with `stored_sorting_key_columns` and `PatchMode::MergeOnKey`, which no longer exist. `isPatchPartSystemColumn` is still used here and still resolves — master dropped the same include and keeps both call sites. The revert does not touch the MATERIALIZED staging this branch was rescoped around: `level_of_column` and `affected_materialized` are still on master, so the premise in the description stands. - `02c205b57da` binds `_sample_factor` to 1 in on-fly mutation expressions, in the same function this branch reshaped. Both sides kept: `getMutationActions` still takes the `MutationChainForRead` built above it, and `bind_sample_factor` is declared next to it for the loop that already merged cleanly. The include sets are the union — `Columns/ColumnConst.h` and `DataTypes/DataTypesNumber.h` from master, `<queue>` from here. Verified on the merge result: `04869`, `04926`, `05023`, `05024` and `01845_add_testcase_for_arrayElement` pass, and both benchmarks are unchanged — flat at 0.11s for 0/10/50/100 MATERIALIZED columns when nothing is recomputed, 0.38 / 0.41 / 0.52 / 0.67s for 1/10/50/100 when one is. `05023` matters most here: it drives a lightweight `UPDATE` with `apply_patch_parts = 1`, the area the revert touches, and is unaffected. Co-Authored-By: Claude Opus 5 <[email protected]>
The tests were added over several rounds, so each took the next free number at the time: 04869, 04926, 05023, 05024. Same-number different-name tests coexist in the suite (`04869_` already holds a dozen unrelated ones), so one number for the whole pull request keeps its tests adjacent in the directory and returns three numbers to the pool. Renames only -- no test content changes. Co-Authored-By: Claude Opus 5 <[email protected]>
`MaterializedColumnDependencies`, added by #114561, already computes for every MATERIALIZED column whether its expression reads an EPHEMERAL one, and the dependency analysis skips those columns through it. That replaced the loop this branch had been collecting the same information in, hence the conflict. Resolved by dropping this branch's own detection and asking the shared node instead, so the fix is one condition on `clear_affected_materialized`. Keeping it there rather than in `emit_materialized_recompute_stages` preserves the documented invariant that the set stays equal to what the recompute writes. The error the fix prevents also changed with #114561: `Missing columns: 'e' while processing 'x + e'` (`UNKNOWN_IDENTIFIER`) is now `There is no column or subcolumn e in table` (`NO_SUCH_COLUMN_IN_TABLE`). Test comment updated to match. Co-Authored-By: Claude Opus 5 <[email protected]>
ClickHouse#114561 made a MATERIALIZED column over an ALIAS column recomputable by replacing the alias reference with the expression it stands for, cast to the alias's declared type. Its test reaches that through `ALTER ... UPDATE` and through an on-fly read, but not through `CLEAR COLUMN`, which builds its recompute set separately. So the path that first surfaced the bug is the one the suite does not exercise. Two cases, both on tables with no EPHEMERAL column so nothing else filters the set: the plain expansion, and a narrowing alias that pins the declared-type cast. The narrowing case needs the `+ 256`. A clear leaves `x` at 0, so with a bare `a UInt8 ALIAS x` the correct expansion and one that dropped the cast would both give 0 and the case would pass either way. With the offset the correct expansion gives `UInt8(0 + 256) = 0` and a cast-less one gives 256. Verified on a binary built from this branch, whose HEAD is `origin/master`. The first case fails with `Code: 47. Missing columns: 'a' while processing: 'a + 1'` on a pre-ClickHouse#114561 binary. Co-Authored-By: Claude Opus 5 <[email protected]>
Closes: #100613
Closes: #50237
Related: #99281
Related: #103182
Related: #115371
Related: #115372
Related: #115638
Scope changed. The staging half of this pull request — recomputing a chain of
MATERIALIZEDcolumns one dependency level at a time during a mutation — landed on master in the meantime via
#103182, which also generalizes it to
APPLY PATCHES, so all of it was dropped here. What remains isthe read path, which master still gets wrong: the read set is closed in
AlterConversions, andMutationsInterpreter::preparekeeps a single line of change, resolvingMATERIALIZEDdefaultsagainst the whole table instead of the read task's columns. The two defects that belong to the
staging path are split out into #115371 and #115372.
Problem
With a mutation still pending, reading a
MATERIALIZEDcolumn that reaches the updated column onlythrough another
MATERIALIZEDcolumn returns the stale on-disk value, while reading the whole chainreturns the recomputed one:
disagrees.
MATERIALIZEDcolumn defined over a subcolumn (m1 MATERIALIZED t.a + 1with a pending
UPDATE t = ...):SELECT m1returns the stale value unless the query happens toselect
tas well.MATERIALIZEDcolumn together with a column the mutation updates fails outright withUNKNOWN_IDENTIFIERwhenever the first one's dependencies are not in the select list, even whenthat column has nothing to do with the mutation.
Root cause
Reading with
apply_mutations_on_flybuilds the pending commands into the read pipeline.AlterConversions::addColumnsRequiredForMaterializeddecides which extra columns must be read so thatthe
MATERIALIZEDcolumns being selected can be recomputed, and it only looked one hop deep:For
m2 MATERIALIZED m1 + 1the only dependency ism1, which is not inall_updated_columns, sonothing is added,
filterMutationCommandsdrops theUPDATE xcommand as irrelevant to the read set,and
m2is returned from disk. Two further details of the same analysis:replaceSubcolumnsToGetSubcolumnFunctionInQuery, som MATERIALIZED t.ais seen to depend ont.arather than ont, and a pendingUPDATE tisfiltered out (or the analysis fails with
UNKNOWN_IDENTIFIERwhen the subcolumn does not resolveagainst
source_columns);MATERIALIZEDcolumn whose expression reads anEPHEMERALcolumn can never be recomputed outsideINSERT, so analysing it against physical columns must be avoided rather than attempted.Solution
Two sites, because the read set has two consumers that must agree.
AlterConversions::addColumnsRequiredForMaterialized— close the read setso the
MATERIALIZEDcolumns in between are read too and the interpreter recomputes the wholechain instead of
filterMutationCommandsdropping theUPDATEas irrelevant.asks of the column it visits whether the interpreter recalculates it, and if so takes its whole
expression, because the stage that rewrites it evaluates that expression against the block —
including the part reading a column no mutation touches (
c MATERIALIZED m1 + y, whereyisuntouched). A column that keeps its stored value contributes nothing, so a chain whose value cannot
change is not read.
replaceSubcolumnsToGetSubcolumnFunctionInQuery, matching whatMutationsInterpreter::preparedoes before analysing the same expression. Without it
m MATERIALIZED t.a + 1is seen to depend ont.awhileall_updated_columnsholdst; the names do not match and a pendingUPDATE tisfiltered out. This is a one-hop defect, independent of the chain.
EPHEMERALcolumns added to the analysis source list.getAllPhysicalexcludes them, soanalysing
me MATERIALIZED x + ethrewUNKNOWN_IDENTIFIERinside this function. Measured onmaster,
SELECT mewith any pendingUPDATEfails this way. Also a one-hop defect, and analysingevery hop of a chain would have multiplied its reach.
EPHEMERALtest mirrors the interpreter's policy, and keeps a pass of its own.MutationsInterpreternever recomputes aMATERIALIZEDcolumn that reads anEPHEMERALone, sosuch a column is not treated as recalculable here either — the read set must not promise a
recomputation the interpreter refuses. It cannot share the loop that looks for a changed
dependency: that loop stops at the first one it finds, while this test quantifies over all of them,
so interleaving them skips it exactly when a dependency is updated.
getMutationStepsruns per read task per part, so each default expression isanalysed at most once per call and each reachability question answered at most once.
MutationsInterpreter::prepare— resolve defaults against the whole tableavailable_columnswas serving two different roles: whichMATERIALIZEDcolumns need recalculating,and which columns their expressions may be resolved against. For a plain
UPDATEthe two coincide. Atable carrying a
MATERIALIZEDcolumn the mutation does not affect breaks the coincidence — itsdependencies are legitimately outside the read set — and the analysis failed with
UNKNOWN_IDENTIFIER, taking the query with it:Deciding whether a column has to be recalculated must not require reading what it reads, so the
default expressions are now resolved against every column of the table. Only an on-fly read has a
narrow list: a materialising mutation passes
getNamesOfPhysical(), so the only columns this addsthere are virtual ones, which a
MATERIALIZEDdefault cannot reference —CREATEandALTERbothreject that.
The list is built on first use. Copying it costs a node per column of the table, the loop needs it
only for a
MATERIALIZEDcolumn the task reads, and an on-fly read reaches it per part. Wideningneed_materialized_analysisinstead would have been wrong:validateUpdateColumnsruns at the end ofthe same block, so guarding the block would drop the check that rejects an
ALTER UPDATEof a key orMATERIALIZEDcolumn on every table withoutMATERIALIZEDcolumns.Taken from #115638
@Avogar tried an alternative on top of this branch in
#115638 and asked for it to be moved here. It is in as of
4bec5ca8a1a, applied verbatim — the test files this branch already carried are byte-identical in it,and
Settings::apply_on_fly_for_readis kept. What it adds over the two sites above:MaterializedColumnDependencies— the dependency graph over a table'sMATERIALIZEDcolumns,built once and shared by the read path and
MutationsInterpreterinstead of being derivedseparately in each, so the two can no longer disagree about how a dependency is spelled. This is
also the graph @Avogar needs in Rebuild skip indices, projections, TTL and MATERIALIZED columns left stale by ALTER MODIFY / UPDATE / CLEAR COLUMN #112717.
filterMutationCommandsputs thecolumns a surviving command reads into the read set, and one of those can itself be a
MATERIALIZEDcolumn of a chain (
DELETE WHERE m2 > 100), which can in turn keep an older command alive. Closingand filtering used to run once each, in that order, so a chain reached from a
DELETEpredicate oran
UPDATEexpression stayed stale. They now iterate until the set stops growing; it only grows andis bounded by the width of the table, so it terminates.
t.a) while the read set is keyed on storagecolumns, which made every read of the table fail with
NO_SUCH_COLUMN_IN_TABLE. Names now gothrough
getNameInStorageon the way in. This one reproduces on master.buildMutationChainForReadshared bygetMutationStepsandgetMutationActions, instead ofeach recomputing the read set and the command filter.
A
MATERIALIZEDcolumn over anALIAScolumnAlso fixed here, in
aeda9610380, because after the extraction there is exactly one place to do it.A
MATERIALIZEDdefault may read anALIAScolumn, and that made every mutation on the tablethrow, including one updating a column the expression never mentions:
The list the default is analysed against is the physical one and an
ALIASis physical-excluded.Merely adding aliases to it would let
TreeRewriterresolve the name, but the expression would thenstill read
aat execution time and no part has such a column, so the recompute stage would fail onit instead. The reference is replaced by the expression it stands for, with
ReplaceAliasByExpressionMatcher— the same visitorIndexDescription::initExpressionInfouses so askip index can reference an
ALIAScolumn.MaterializedColumnDependencieshands the same expressionto the dependency analysis and to the recompute stage, so one expansion reaches both; it runs before
the subcolumn rewrite, so a subcolumn reached through an alias is normalised too.
Unlike the
EPHEMERALcase next to it there is no trade-off:mrecalculates correctly from thestored
x, and anALIAScolumn is recomputed per query so it can never itself be stale.Not proposed for backport
The change started as a narrow read-path fix, but with the dependency graph extracted into a new
component shared by two subsystems it is no longer a good backport candidate, and it is not labelled
for one.
Coverage
Regression test
04869_materialized_chain_on_fly_readcovers six cases, each measured individuallyagainst master
5bd006cd298:UNKNOWN_IDENTIFIER, because the surviving command makes the interpreter analyse a default whosedependency is not in the read set;
the same reason, after the command is narrowed and loses the assignment the chain depends on;
DELETEthat keeps a command alive while the set of updated columns stays empty —returns the stale value, since the analysis is skipped entirely;
recalculated column reading an untouched one — stale value or
UNKNOWN_IDENTIFIERdepending on theselect list;
EPHEMERAL-derived column — stale value andUNKNOWN_IDENTIFIERrespectively.
04926_on_fly_mutation_read_set_closurecovers the cases the read-set closure loop repairs: the chainreached from a pending
DELETEpredicate, a subcolumn spelled as written in a command, and the casesthat must not move.
05024_materialized_over_alias_column_mutationcovers theALIAScase, measured both ways on a Debugbuild: without the expansion
UPDATE z = 5andUPDATE x = 20both throwUNKNOWN_IDENTIFIER; withit the first leaves
malone and the second givesx, a, m = 20, 120, 121, on the settled part and onthe on-fly read alike.
05023_materialized_ephemeral_stale_warningis unchanged and still passes.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed reading a table while a mutation is in progress: a
MATERIALIZEDcolumn could return a stale value, and selecting one together with an updated column could fail with an error.Workflow [PR]
Sync PR [sync-upstream/pr/114561]
Version info
26.9.1.4(included in26.9and later)