Skip to content

See a non-deterministic function inside a column definition in mutation pruning - #117273

Merged
alexey-milovidov merged 9 commits into
masterfrom
fix-mutation-pruning-alias-nondeterministic
Sep 20, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
fix-mutation-pruning-alias-nondeterministic

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #117115
Related: #110968
Related: #117113

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 ALTER DELETE/ALTER UPDATE silently skipping rows when the predicate references an ALIAS
column whose definition contains a non-deterministic function such as now. The default-enabled
optimize_mutations_with_partition_pruning folded it at submission time and narrowed the mutation's
block_numbers, so a partition matching only the execution-time value was left out while the mutation
still reported is_done = 1.

Description

contains_nondeterministic_function in MergeTreeData::getPartitionIdsPrunedByPredicate walks the
raw predicate AST, so a non-deterministic function hidden inside a column definition is invisible to
it: p < r with r UInt32 ALIAS toUnixTimestamp(now()) contains no function name to inspect. The
pruning analysis then resolves the ALIAS against the storage — that is deliberate, it is what makes
pruning work for computed columns — and folds now to its submission-time value anyway. The
asynchronous execution re-expands the definition and evaluates now again, later.

The check now follows a column's own ALIAS/MATERIALIZED/DEFAULT expression. Column definitions
form a DAG, so the recursion terminates.

Worth noting separately: the pre-existing allow_nondeterministic_mutations validation
(MutationsInterpreter::validateNonDeterministicMutationsForStorage) has the same raw-AST blindness,
which is why the statement is accepted on a replicated table at pure default settings. This PR only
stops the pruning from acting on it; whether such a mutation should be accepted is a separate
question.

Test 05076_mutation_partition_pruning_alias_nondeterministic asserts the resulting
block_numbers.partition_id, and that a deterministic ALIAS is still pruned.


Workflow [PR]
Sync PR [sync-upstream/pr/117273]

…on pruning

Mutation partition pruning refuses a predicate containing a query-time non-deterministic
function, because it folds the function at submission time while the asynchronous execution
evaluates it again - possibly much later, or on another replica - so a partition matching only
the execution-time value escapes the mutation.

The check walked the raw predicate AST, so `now` inside an `ALIAS` column's definition was
invisible: `p < r` with `r UInt32 ALIAS toUnixTimestamp(now())` contains no function name to
inspect. The pruning analysis then resolves the `ALIAS` against the storage - that is deliberate -
and folds `now` anyway. The pre-existing `allow_nondeterministic_mutations` validation has the
same raw-AST blindness, so the statement is accepted at default settings.

The check now follows a column's own `ALIAS`/`MATERIALIZED`/`DEFAULT` expression.

Closes: #117115
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [07041ac]

Summary: ✅


AI Review

Summary

This PR fixes the original mutation-partition-pruning bug for direct ALIAS references and for the simple lambda-shadowing cases covered by the new test, but the current lambda fix is still incomplete. The determinism walk now carries lambda-bound names into recursively scanned column definitions, even though those definitions are later analyzed at table scope, so a non-deterministic function hidden behind an alias chain can still be missed and let pruning exclude a partition that only matches the execution-time value.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:10022] self(column_default->expression, self) inherits the caller's lambda_parameters, but a stored column definition is authored at table scope and the real ALIAS expansion paths analyze it that way (src/Storages/ReplaceAliasByExpressionVisitor.cpp:87-95, src/Analyzer/Resolve/QueryAnalyzer.cpp:4601-4652). With s UInt32 ALIAS toUnixTimestamp(now()), r UInt32 ALIAS s + 1, and ALTER TABLE ... DELETE WHERE p = 1 AND arrayExists(s -> s = r, arr), the recursive walk reaches r from inside the lambda body and then scans s + 1 with the lambda's s still bound, so it suppresses the nested read of table-column s and misses the hidden now. That leaves the original silent-overpruning bug reachable through an alias chain, and because followed_column_definitions memoizes r, a later non-lambda reference to r in the same predicate is skipped too. Suggested fix: recurse into column_default->expression with a fresh table-scope lambda binding set (save/restore the caller state around that recursive call), then add a regression case where an alias referenced from inside a lambda expands to another alias containing a non-deterministic function.
Final Verdict

❌ Changes requested. The remaining alias-chain case still breaks the PR's correctness contract: mutation partition pruning can miss a non-deterministic function and silently leave matching rows untouched.

LLVM Coverage Report

Measured on commit 07041ac.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.70% +0.10%

Changed lines: Changed C/C++ lines covered: 39/42 (92.86%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

The definition-following hook is in the right function — the single consumer serves background mutations, lightweight deletes, and lightweight updates alike, and the raw-AST walk means the folded-lambda blind spot of DAG walks does not apply here. But the lookup keys on the identifier's full compound name via getDefault(identifier->name()), which is exact-match, so spellings the analyzer resolves to the very same alias slip past by construction:

  • Qualified column name: ALTER TABLE t_q DELETE WHERE p < t_q.r — the identifier's name is t_q.r, getDefault returns nothing, and the analyzer branch below resolves it against the TableNode and folds now exactly as before. Verified on current master that both spellings reach the same fold: with r UInt32 ALIAS toUnixTimestamp(now()) and partitions 1 and 2, both DELETE WHERE p = t_q.r % 2 + 1 and DELETE WHERE p = r % 2 + 1 record block_numbers.partition_id = ['2']. With this PR the bare spelling is caught and the qualified spelling still prunes — one extra token on the PR's own test case.
  • Subcolumn of an alias: r Tuple(a UInt32, b UInt32) ALIAS ..., predicate WHERE p < r.a — same exact-match miss, and transitively r2 UInt32 ALIAS r.a re-hits the compound identifier one level down.

A lookup that also tries successively stripped compound prefixes (over-matching is safe here — the cost is only lost pruning) would close both.

Two smaller notes: the recursion has no memoization or visited set, so a diamond-shaped definition chain (c1 ALIAS x + 1; c2 ALIAS c1 + c1; ... c40 ALIAS c39 + c39, predicate referencing c40) walks an exponential number of nodes at submission time — a NameSet of already-cleared columns fixes that and doubles as a cycle backstop for hand-edited metadata. And the sibling guard contains_deferred_set did not get the definition-following treatment in either this PR or #117272, so a deferred IN <table> set hidden behind an alias still prunes with submission-time contents (details and the rigged repro in the comment on #117272; the execution side of that spelling is currently #117276).

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 07041ac53 with master 930ccf281 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 01b8f1c9f; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 36 s compile time in total, 7 of them have a recent master baseline.

Job report

…arriers

Two holes in the definition-following check:

- `getDefault` is keyed by the bare storage column name, while the identifier in the predicate is
  raw text: `t.r`, `db.t.r` and the subcolumn spelling `r.a` all resolve to the same `ALIAS`
  definition in the analysis below, but missed the lookup, so the silent-skip bug stayed reachable
  through them. Every contiguous range of the identifier's name parts is looked up now - an
  accidental match with an unrelated column of that name only costs a pruning opportunity.

- Following a stored `DEFAULT`/`MATERIALIZED` definition was a needless pessimization:
  `QueryAnalyzer` attaches an expression to `ALIAS` columns alone, a physical column is read as it
  was written, so its definition cannot diverge between the analysis and the execution. A table
  like `d Date DEFAULT today()` partitioned by `toYYYYMM(d)` stopped pruning `DELETE WHERE d =
  '2026-01-15'`. Only the computed carriers (`ALIAS`, `EPHEMERAL`) are followed now.

A definition is followed once, so a diamond-shaped chain of definitions is no longer walked an
exponential number of times, and a cycle in hand-edited metadata cannot loop.

`05076_mutation_partition_pruning_alias_nondeterministic` covers the qualified and the subcolumn
spelling, and pins that a stored `DEFAULT` partition column still prunes a literal predicate.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both blocking findings are addressed in afbf08e (name-part normalization for qualified/subcolumn spellings; only ALIAS/EPHEMERAL are followed, so stored DEFAULT/MATERIALIZED pruning is not regressed), together with the memoization @zlareb1 asked for, which also backstops a cycle in hand-edited metadata.

The sibling contains_deferred_set guard deliberately stays as it is here: that spelling is tracked in #117272 / #117276, and mixing it into this fix would make two independent behaviour changes share one test.

Verified locally against a private server: 05076_mutation_partition_pruning_alias_nondeterministic passes, and so do 04035, 04612, 04696, 04697, 04757, 04849, 04903, 04907, 04909, 05024 — the whole mutation-pruning family.

@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 4, 2026
alexey-milovidov and others added 2 commits September 10, 2026 05:03
The `ALTER ... DELETE` writes the mutation entry to ZooKeeper, but it becomes visible in
`system.mutations` only after the replica pulls it into its queue, which happens asynchronously.
With `mutations_sync = 0` the test read `system.mutations` right after the `ALTER` and, in the
Fast test run, missed the second mutation of the first table:

    0000000000	['1','2']
   -0000000001	['1']

Pull the queue explicitly with `SYSTEM SYNC REPLICA ... PULL` before every read instead of racing
against the queue-updating task. The test now passes 15 runs in a row locally.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was a week stale) and fixed the only CI red, the Fast test failure of this PR's own test.

The failure was a race in the test, not in the fix: ALTER ... DELETE writes the mutation entry to ZooKeeper, but it only becomes visible in system.mutations once the replica pulls it into its queue, which happens asynchronously. With mutations_sync = 0 the test read system.mutations immediately after the ALTER and missed the second mutation of the first table:

 0000000000	['1','2']
-0000000001	['1']

Every read is now preceded by SYSTEM SYNC REPLICA <table> PULL, which calls pullLogsToQueue synchronously and that in turn calls updateMutations, so the entry is guaranteed to be there. Verified locally against a private server: 15 consecutive runs of 05076_mutation_partition_pruning_alias_nondeterministic pass, and so does the rest of the mutation-pruning family (04035, 04612, 04613, 04614, 04624, 04696, 04697, 04757, 04820, 04849, 04903, 04907, 04909, 05024).

The two open threads are already answered in afbf08e; no code change in this round.

alexey-milovidov and others added 3 commits September 10, 2026 18:33
…determinism check

A lambda keeps its parameters as plain `ASTIdentifier`s, so the walk that follows
an `ALIAS`/`EPHEMERAL` column definition mistook `x` in
`arrayExists(x -> x = 1, arr)` for a storage column `x` and, if that column hid
a non-deterministic function, disabled pruning for a deterministic predicate.
Carry the parameters of the enclosing lambdas through the recursion and skip an
identifier whose first name part is bound by one of them.

Rename the test to `05227_...` to avoid a number collision on master and add
lambda cases: a shadowing parameter (pruned), a two-parameter lambda (pruned),
the same name outside the lambda (not pruned) and the alias referenced from
inside the body under another name (not pruned).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
if (column_default->kind != ColumnDefaultKind::Alias && column_default->kind != ColumnDefaultKind::Ephemeral)
continue;

if (self(column_default->expression, self))

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.

The lambda-bound names are correct for the raw predicate AST, but this recursive call reuses them when walking a stored column definition. That changes the scope: the definition was authored at table scope, and the real ALIAS resolver analyzes it that way (src/Storages/ReplaceAliasByExpressionVisitor.cpp:87-95, src/Analyzer/Resolve/QueryAnalyzer.cpp:4601-4652), so a lambda parameter must not shadow identifiers inside the column's own expression.

A concrete miss is:

CREATE TABLE t
(
    p UInt32,
    arr Array(UInt32),
    s UInt32 ALIAS toUnixTimestamp(now()),
    r UInt32 ALIAS s + 1
)
...
ALTER TABLE t DELETE WHERE p = 1 AND arrayExists(s -> s = r, arr);

Inside the lambda body we bind s, then follow r here and recurse into s + 1 with the same lambda_parameters. The inner s is treated as the lambda argument at lines 10001-10003, so the walk never reaches the nested now even though mutation execution expands r at table scope and evaluates it later. Because followed_column_definitions memoizes r, a later non-lambda use of r in the same predicate would be skipped too. I think the recursive scan of column_default->expression needs to run with a fresh table-scope lambda set, then restore the caller bindings afterward.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok for a follow-up.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

azat pushed a commit to azat/ClickHouse that referenced this pull request Oct 5, 2026
…pruning

`MergeTreeData::getPartitionIdsPrunedByPredicate` refuses to prune a mutation
whose predicate can see a query-time non-deterministic function, because the
pruning pass folds it at submission time while the asynchronous execution
evaluates it again later. Since ClickHouse#117273 the check also follows an
`ALIAS`/`EPHEMERAL` column's own expression, and it carries the parameters of the
enclosing lambdas so that `arrayExists(x -> x = 1, arr)` does not mistake `x` for
a storage column of that name.

That descent ran with those parameters still in scope. For
`s ALIAS toUnixTimestamp(now())`, `r ALIAS s + 1` and the predicate
`p = 1 AND arrayExists(s -> s = r, arr)`, the walk enters the lambda, binds `s`,
meets `r`, follows `r`'s definition `s + 1`, and there rejects the definition's
own `s` as the lambda parameter. `toUnixTimestamp(now())` is never reached,
`plus` is deterministic, so the check reports the whole predicate deterministic
and the mutation is pruned with the submission-time value. Rows in the partitions
that fold excluded are never mutated and `system.mutations` reports
`is_done = 1`. Measured on a pristine build: `block_numbers.partition_id` is
`['1']` where it must be `['1','2']`. The same predicate with the parameter
renamed is correctly left unpruned, which is the asymmetry the report named.

A column definition is resolved once at table scope, not at the point of use, so
the predicate's lambda bindings must not be visible inside it.
`QueryAnalyzer::getColumnNodeMap` resolves an `ALIAS` column's expression in a
scope built from the table expression, and
`ReplaceAliasByExpressionMatcher::visit` expands a definition with an explicitly
empty bound-name set for the same reason. That is also why the divergence is
real: the mutation genuinely re-evaluates `now()` later.

Save and clear the parameters around that one descent and restore them
unconditionally. Clearing the set can only enable column lookups inside a
definition, so the check can only move from "prune" to "do not prune"; it cannot
widen pruning, and the worst case is a lost pruning opportunity, which is the
trade-off the surrounding comment already accepts.

The memoization of followed definitions needs no separate change. The verdict for
a definition now depends only on the storage metadata, never on the caller's
scope, so memoizing it per column name is sound, and it remains the termination
backstop for diamond-shaped definition graphs. Keying it by name and scope
instead would leave the wrong verdict in place and only stop it spreading.

Raised as a review comment on ClickHouse#117273,
ClickHouse#117273 (comment), and
deferred there with "Ok for a follow-up",
ClickHouse#117273 (comment). Also
reported as ClickHouse#121167.

The regression test appends three arms to the file ClickHouse#117273 added. The first is
the defect and fails on a pristine build. The second pins the restore: after a
deterministic definition is walked, the enclosing binding must be back,
otherwise `s` stops being the parameter and the non-determinism behind it
disables pruning. The third pins the boundary in the other direction: following
`e ALIAS d + 1` at table scope reaches the deterministic `d ALIAS k + 1` even
though the lambda binds the name `d`, so the predicate still prunes. Declining
to prune whenever a followed definition mentions a bound name would be safe but
would lose that, and without the third arm the test accepts it.

Each arm was measured against an implementation that breaks only that arm: the
pristine build reddens the first, a variant that clears the parameters without
restoring them reddens the second, and a variant that declines on a mentioned
bound name reddens the third. In each case the other two arms and every
pre-existing line stayed unchanged, so no arm is redundant. Narrowing uses the
deterministic `p = 1` rather than `p < r`, because a comparison against a unix
timestamp keeps both partitions whether or not pruning happened.

Co-Authored-By: Claude Opus 5 <[email protected]>
@Algunenano

Copy link
Copy Markdown
Member

The test is flaky in private

@Algunenano
Algunenano restored the fix-mutation-pruning-alias-nondeterministic branch October 5, 2026 12:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). 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

4 participants