Skip to content

Treat functions written without parentheses (now, today) as non-deterministic in mutations - #124127

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/mutation-niladic-functions-without-parentheses
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/mutation-niladic-functions-without-parentheses

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124002

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

ALTER UPDATE, ALTER DELETE and DELETE FROM on Replicated* tables with the default allow_nondeterministic_mutations = 0 now reject a function written without parentheses (now, today, CURRENT_DATE, CURRENT_TIMESTAMP, user) and a reference to an ALIAS column with a non-deterministic definition, as they already rejected now(). Set allow_nondeterministic_mutations = 1 to run them as before. Such a mutation is also no longer pruned to the partitions that match at submission time, which could skip rows. Closes #124002.

Description

now, today, CURRENT_DATE, user and similar functions can be written without parentheses: the analyzer resolves such an identifier as a call when no column, alias or lambda parameter binds the name. The mutation determinism checks look only for AST function nodes, so they took it for a column:

  • On 26.9.9.28, ALTER TABLE t DELETE WHERE d < today on a ReplicatedMergeTree is pruned to block_numbers.partition_id = ['20000101'] (today() gets both). On master, DELETE WHERE ts < now with PARTITION BY ts reaches is_done = 1 and leaves a row matching ts < now() when the mutation runs.
  • On 26.8.10.6, with the default allow_nondeterministic_mutations = 0, it is accepted on a Replicated* table (d < today() is rejected), so each replica evaluates it at its own time.

Both checks now use the analyzer's resolution of the command against the table, so a column, alias or lambda parameter named now still binds the name:

  • Pruning gives up when the analyzed ActionsDAG of the predicate has a non-deterministic node, including calls inside ALIAS definitions and lambdas.
  • The allow_nondeterministic_mutations check resolves the assignments and the predicate against the current metadata (a column added by the same ALTER is seen) and rejects a non-deterministic function, including one in an ALIAS column definition (d < r for r Date ALIAS today() is accepted on master). Like the check of virtual columns, it analyzes the command with the name resolution settings of both the query and the background context that executes the mutation.

The mutations_execute_nondeterministic_on_initiator rewrite is unchanged: it replaces today(), and a bare today is rejected by the check. The apply_mutations_on_fly read path is not changed.

The new test fails on master 4f752f7e6fcf and passes with the fix (50/50 randomized runs).


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

groeneai and others added 2 commits October 6, 2026 01:04
…utations

`now`, `today`, `CURRENT_DATE`, `user` and other functions that allow omitting
parentheses are resolved by the analyzer as calls when no column, alias or lambda
parameter binds the name. The determinism checks of a mutation walk the raw AST and
only look at function nodes, so such an identifier passed as a column:

- partition pruning folded it to its submission-time value and narrowed the
  mutation to the partitions matching then, so rows of a partition that matches
  when the mutation runs were not mutated while the mutation reached is_done;
- the Replicated* guard accepted it with allow_nondeterministic_mutations = 0;
- mutations_execute_nondeterministic_on_initiator did not replace it.

Pruning now also gives up when the analyzed ActionsDAG of the predicate holds a
non-deterministic node: the analysis has already resolved the calls, including
those inside ALIAS definitions and lambda bodies. The linear DAG scan is used
instead of a recursive walk from the predicate node, which would revisit shared
subtrees of a diamond-shaped ALIAS chain.

The guard and the initiator rewrite run on the raw AST, and the rewrite has to edit
it, so they share one helper that makes such calls explicit on a copy, resolving a
name like the analyzer: a table column, a lambda parameter or an alias of the same
scope binds it first, and an alias is not visible inside its own expression. The
rewrite runs before the column commands of the same ALTER, so a column that the
ALTER adds or renames binds the name as well, while a column that an earlier
command of it drops or renames away does not. The guard runs after them, so it
reads the metadata past the per-query cache, which still holds the snapshot taken
before the ALTER. The rewrite keeps the alias of a call that it replaces with its
value, so the rest of the expression can still refer to it. The
apply_mutations_on_fly read path is unchanged: it re-checks already stored
commands on every read.

Closes ClickHouse#124002

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the column-tracking comment in parseAlterCommandSegments to one line and drop an obvious member comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 6, 2026
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 5 rounds, 11 findings) plus my own review (5 rounds, 10 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ The determinism guard read the per-query metadata snapshot, so in ALTER ... ADD COLUMN today ..., UPDATE ... WHERE today = ... it did not see the new column and rejected the mutation (MutationsInterpreter.cpp) AGREE, fixed the guard reads the current table metadata; test leg added
2 ⚠️ Any ADD/RENAME COLUMN in the same ALTER turned off the initiator evaluation for every mutation of the query (InterpreterAlterQuery.cpp) AGREE, fixed only the names that the query adds or renames bind; test legs added
3 ⚠️ An alias bound its own definition, so d < (today AS today) escaped the guard and the initiator evaluation (MutationsNonDeterministicHelpers.cpp) AGREE, fixed an alias is not visible inside its own expression, as in the analyzer; test legs added
4 💡 No test for the initiator evaluation of an UPDATE assignment AGREE, fixed test leg added
5 ⚠️ The initiator evaluation dropped the alias of the replaced call, so d < (today AS t) AND t > ... failed with UNKNOWN_IDENTIFIER (the parenthesized spelling already did on master) AGREE, fixed the literal keeps the alias; test legs for both spellings
6 ⚠️ A name that an earlier command of the same ALTER drops or renames away was still treated as a column, so the initiator kept it bare AGREE, fixed such a name is resolved as the function; DROP and RENAME legs added
7 💡 An alias defined in an UPDATE assignment binds the same name in the predicate (UPDATE v = (p AS now) WHERE now = 1) AGREE, not changed the stage resolves the assignments and the filter as one expression list (MutationsInterpreter.cpp), unchanged from master
8 💡 A mutation ordered before an ADD COLUMN of the same name keeps the name not changed whether it runs before the replica applies the new metadata is not fixed, so keeping the name (as master does) is the safe choice
9 💡 No separate test leg for the lightweight UPDATE pruning DISAGREE the new check is one statement shared by both paths (MergeTreeData.cpp)
10 ⚠️ A scalar function on the right side of IN (d IN toDate(today)) hid a bare call from the guard and the initiator evaluation (MutationsNonDeterministicHelpers.cpp) AGREE, fixed only a table function on the right side of IN is skipped; guard and initiator legs added
11 ⚠️ A name that the same ALTER renames to and then drops before the mutation was still treated as a column (InterpreterAlterQuery.cpp) AGREE, fixed the column commands before a mutation are applied in order; rename-then-drop leg added
12 ⚠️ A column whose name only starts with the name and a dot (now.x UInt8) made a bare now count as a column, while the analyzer reads now as a Nested only from Array columns (MutationsNonDeterministicHelpers.cpp) AGREE, fixed the same Array rule as the analyzer; guard leg and a Nested control added
13 💡 An alias inside its own definition also hid a same-named alias of an outer scope ((k AS today) = 106 AND arrayExists(x -> (today AS today) > 0, [k])) AGREE, fixed only the alias of the defining scope is hidden, as in the analyzer; initiator leg added
14 ⚠️ RENAME COLUMN IF EXISTS of a missing column to a function name in the same ALTER still makes that name a column for the initiator evaluation DISAGREE the guard then reads the altered table, finds no such column and rejects the mutation as non-deterministic; with allow_nondeterministic_mutations = 1 it is stored as on master. Not modelled further
15 💡 A Nested column that the same ALTER adds as a dotted Array child (ADD COLUMN `today.a` Array(UInt8)) does not make the bare prefix a column for the initiator evaluation, which then replaces it with a Date AGREE, not changed needs such a mixed ALTER with mutations_execute_nondeterministic_on_initiator = 1; a Nested-shaped predicate is then rejected at submission. Not modelled further, like row 14

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-8:20261006-014200

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05325_mutation_niladic_function_without_parentheses on a ReplicatedMergeTree with stopped replication queues: on master 503013e8cc4f the 11 bare-spelling ALTER/DELETE statements are accepted with allow_nondeterministic_mutations = 0, 5 bare-spelling predicates get block_numbers.partition_id = ['20000101'] and the initiator rewrite keeps CURRENT_DATE. Same on official 26.9.9.28 (pruning) and 26.8.10.6 (guard).
b Root cause explained? The analyzer resolves a bare today as today() only when nothing binds the name. The three mutation checks walk the raw AST and only look at function nodes, so the identifier passed as a column; the pruning analysis then folded it to its submission-time value.
c Fix matches root cause? Yes. Pruning decides on the analyzed DAG, which already holds the resolved call; the guard and the rewrite resolve bare names with the analyzer's binding order (columns, lambda parameters, aliases) on a copy.
d Test intent preserved / new tests added? One new .sql test: pruning, guard and rewrite legs, controls where a column, a Nested column, a lambda parameter or an alias binds the name, and an ALTER that adds, renames or drops a column next to the mutation. Existing tests unchanged.
e Both directions demonstrated? Yes. FAIL on the master build, OK on the fix build; each of 18 deletion mutants of the fix reddens the test.
f Fix is general across code paths? ALTER DELETE/UPDATE, DELETE FROM, lightweight UPDATE pruning, ALIAS definitions and lambda bodies. The apply_mutations_on_fly read path is left unchanged (offered in the description).
g Fix generalizes across inputs (params/datatypes/wrappers)? Name resolution, not types: every function with allowsOmittingParentheses() (now, today, CURRENT_DATE, CURRENT_TIMESTAMP, localtime, user, currentDatabase, ...), any case, in assignments, predicates, lambdas; a name. prefix binds the name only for Array columns, as in the analyzer.
h Backward compatible? (maintainer-approved exception only) Such a mutation on a Replicated* table is now rejected exactly like the parenthesized call, with the same escape hatches. No setting or format change.
i Invariants and contracts preserved? Checks still run on copies; the stored command changes only under mutations_execute_nondeterministic_on_initiator = 1, and a call replaced there keeps its alias. The pruning change can only turn "prune" into "do not prune".

Session id: cron:clickhouse-impl-slot-40:20261006-005300

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78f6f6f]

Summary: ✅


AI Review

Summary

This PR makes mutation validation and partition pruning recognize non-deterministic functions written without parentheses, including calls inside ALIAS definitions, and validates the submitting and background name-resolution settings. No unresolved findings remain at 78f6f6f055e6. The focused stateless regression 05325_mutation_niladic_function_without_parentheses passed with the PR's CI binary.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 6, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Oct 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 78f6f6f05 with master 989ecd896 (stripped binary size, per-symbol sizes and ThinLTO time; 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

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

Job report

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai this seems to be an over-engineered solution. Can you just parse the functions written without parentheses as a parenthesized expression?

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

A parser-level rewrite would change queries that use these names as columns. user, database and schema are aliases of currentUser and currentDatabase that also allow omitting parentheses: on master SELECT database returns currentDatabase(), while SELECT database FROM system.tables returns the column. Parsed as a call, ALTER TABLE t DELETE WHERE database = 'x' would compare currentDatabase() instead of the column on every table that has such a column. Only name resolution can tell the two apart.

I agree the helper is too much, though: it re-implements the analyzer's name binding. I'll replace it with the analyzer itself: the allow_nondeterministic_mutations check will resolve the predicate and the UPDATE expressions against the table, as partition pruning already does, and reject a non-deterministic node. The mutations_execute_nondeterministic_on_initiator rewrite (off by default) stays as on master, so now() is still frozen there, and with the default allow_nondeterministic_mutations = 0 a bare now gets the error from the check. That removes the helper and the InterpreterAlterQuery changes.

Replace the AST helper that re-implemented the analyzer's name binding
(columns, lambda parameters, aliases, Nested, columns added, renamed or
dropped by the same ALTER) with the analyzer itself: for UPDATE and DELETE
commands on Replicated tables with allow_nondeterministic_mutations = 0,
the check resolves the assignments and the predicate against the current
table metadata and rejects a non-deterministic function node, including a
constant folded from one. A column is not followed into its ALIAS
definition, as before.

The mutations_execute_nondeterministic_on_initiator rewrite stays as on
master: it replaces explicit calls such as today(), and a bare `today` is
rejected by the check instead.

The metadata is read bypassing the query metadata cache, so a column added
by an earlier command of the same ALTER is seen.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

Done in dcdacd5: the helper and the InterpreterAlterQuery changes are gone, and the source change is now +68/-2 in MutationsInterpreter.cpp and MergeTreeData.cpp. I updated the PR description accordingly.

The analyzer resolves a reference to an `ALIAS` column into a `ColumnNode`
whose child is the resolved definition. The walk stopped at every column, so
`DELETE WHERE d < r` for `r Date ALIAS today` (or `ALIAS today()`) was still
accepted on a `Replicated*` table with `allow_nondeterministic_mutations = 0`,
and each replica evaluated `today` at its own time. Partition pruning already
treats such a definition as non-deterministic; the check now does too.

Each reference to an `ALIAS` column is a clone of its definition, so the walk
is linear in the size of the tree the analyzer already built.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ENGINE = ReplicatedMergeTree('/clickhouse/tables/{database}/t_guard', 'r1') PARTITION BY d ORDER BY k;
INSERT INTO t_guard (d, k) VALUES ('2000-01-01', 1), ('2100-01-01', 2);
SYSTEM STOP REPLICATION QUEUES t_guard;
ALTER TABLE t_guard DELETE WHERE d < today(); -- { serverError BAD_ARGUMENTS }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai this is backward incompatible

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes. On a Replicated* table with the default allow_nondeterministic_mutations = 0, these are accepted on master and rejected with BAD_ARGUMENTS here:

  • a function written without parentheses (today, now, CURRENT_DATE, user, ...) in the predicate or in an UPDATE expression. 26.8.10.6 accepts it, 26.3.33.24 rejects it as a missing column.
  • a reference to an ALIAS column with a non-deterministic definition, including r Date ALIAS today().

This line itself (today()) is rejected on master too.

I changed the changelog category to Backward Incompatible Change, and the entry says that allow_nondeterministic_mutations = 1 runs them as before. If you would rather not break them, I can drop the check change and keep only the partition-pruning fix in MergeTreeData.cpp: it accepts everything master accepts and still fixes the DELETE that reaches is_done = 1 with matching rows left, but the allow_nondeterministic_mutations part of #124002 then stays as on master. Should I drop it?

groeneai and others added 2 commits November 4, 2026 13:38
`validateNonDeterministicMutationsForStorage` reports a non-deterministic
function or a subquery found in the AST even when an expression of the
mutation cannot be analyzed (`InterpreterAlterQuery` calls it ahead of the
full validation for that reason). The analyzer-based check ran inside the
same per-command loop, so a command that does not analyze threw
`UNKNOWN_IDENTIFIER` before a later command's `now()` was reported:
`ALTER TABLE t DELETE WHERE missing = 1, UPDATE v = toUnixTimestamp(now()) WHERE 1`
on a `ReplicatedMergeTree` returned code 47 instead of 36. Resolve the
expressions in a second loop, after the AST checks of every command and
before the virtual column check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-bugfix Pull request with bugfix, not backported by default labels Nov 4, 2026
A mutation is executed with the settings of the background context, which
may resolve an identifier differently from the query that submitted it. With
`analyzer_compatibility_prefer_alias_over_subcolumn = 1` in the query and
the default in the background, `t.r` was checked as the physical column `r`
but executed as the element of an `ALIAS` column `t Tuple(r ...) ALIAS
tuple(rand64())`, so a non-deterministic mutation was accepted with
`allow_nondeterministic_mutations = 0`.

The check of virtual columns already analyzed both interpretations. Move the
creation of their contexts into a helper and use it for the check of
functions as well. The helper also varies
`analyzer_compatibility_allow_compound_identifiers_in_unflatten_nested`, the
remaining setting that changes what an identifier binds to in a single-table
scope: with it disabled in the background profile, a bare `now` next to a
column `now.a.b` was checked as the `Nested` column but executed as `now()`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backward-incompatible Pull request with backwards incompatible changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mutation determinism guard treats niladic now/CURRENT_DATE as a column

2 participants