Repository navigation
See a non-deterministic function inside a column definition in mutation pruning - #117273
Conversation
…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
|
Workflow [PR], commit [07041ac] Summary: ✅
AI ReviewSummaryThis PR fixes the original mutation-partition-pruning bug for direct Findings❌ Blockers
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 ReportMeasured on commit 07041ac.
Changed lines: Changed C/C++ lines covered: 39/42 (92.86%) · Uncovered code |
|
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
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 ( |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 36 s compile time in total, 7 of them have a recent master baseline. |
…g-alias-nondeterministic
…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.
|
🕵 Both blocking findings are addressed in afbf08e (name-part normalization for qualified/subcolumn spellings; only The sibling Verified locally against a private server: |
…g-alias-nondeterministic
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]>
|
🕵 Merged The failure was a race in the test, not in the fix: Every read is now preceded by The two open threads are already answered in |
…g-alias-nondeterministic
…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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Ok for a follow-up.
…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]>
|
The test is flaky in private |
Closes: #117115
Related: #110968
Related: #117113
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
ALTER DELETE/ALTER UPDATEsilently skipping rows when the predicate references anALIAScolumn whose definition contains a non-deterministic function such as
now. The default-enabledoptimize_mutations_with_partition_pruningfolded it at submission time and narrowed the mutation'sblock_numbers, so a partition matching only the execution-time value was left out while the mutationstill reported
is_done = 1.Description
contains_nondeterministic_functioninMergeTreeData::getPartitionIdsPrunedByPredicatewalks theraw predicate AST, so a non-deterministic function hidden inside a column definition is invisible to
it:
p < rwithr UInt32 ALIAS toUnixTimestamp(now())contains no function name to inspect. Thepruning analysis then resolves the
ALIASagainst the storage — that is deliberate, it is what makespruning work for computed columns — and folds
nowto its submission-time value anyway. Theasynchronous execution re-expands the definition and evaluates
nowagain, later.The check now follows a column's own
ALIAS/MATERIALIZED/DEFAULTexpression. Column definitionsform a DAG, so the recursion terminates.
Worth noting separately: the pre-existing
allow_nondeterministic_mutationsvalidation(
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_nondeterministicasserts the resultingblock_numbers.partition_id, and that a deterministicALIASis still pruned.Workflow [PR]
Sync PR [sync-upstream/pr/117273]