Skip to content

Provide _table and _database virtual columns to mutations - #117724

Merged
Avogar merged 27 commits into
masterfrom
fix/mutation-table-virtual-column
Nov 3, 2026
Merged

Avogar merged 27 commits into
masterfrom
fix/mutation-table-virtual-column

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

MergeTreeSequentialSource, which reads parts for mutations and merges, filled the constant virtual fields _part_index, _part_starting_offset and _sample_factor, but not _table and _database, which ReadFromMergeTree publishes for regular reads. A mutation referencing either column (ALTER TABLE ... UPDATE v = _table, ALTER TABLE ... DELETE WHERE _table = ..., lightweight DELETE) failed in MutatePlainMergeTreeTask with Unexpected const virtual column: _table (NO_SUCH_COLUMN_IN_TABLE) and kept retrying.

The fix publishes both fields in createMergeTreeSequentialSource, the same values ReadFromMergeTree uses. New test 05227_mutation_table_database_virtual_columns covers UPDATE ... = _table, UPDATE ... = _database, DELETE WHERE _table = ... and a lightweight DELETE filtered on _database.

_table, _database and _disk_name are declared with deterministic = false: replicas of one ReplicatedMergeTree table may have different local names or disks, so a mutation reading them would produce different parts on different replicas. The guard MutationsInterpreter::validateNonDeterministicMutationsForStorage only scanned for non-deterministic functions and subqueries; it now also rejects non-deterministic virtual columns on Replicated tables unless allow_nondeterministic_mutations = 1, with a real column of the same name shadowing the virtual one. To find them, the mutation expressions are resolved with the analyzer against the table, the same way the mutation is executed, so a virtual column is caught however it is reached: through a table qualifier, an ALIAS / EPHEMERAL column or its subcolumn, or a Nested prefix. _sample_factor, _part_index and _part_starting_offset are constants in a mutation and stay allowed. New test 05228_mutation_table_database_virtual_columns_replicated covers the rejection, the deterministic controls and the escape hatch.

Found via the Upgrade check (amd_release) red of #114054: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114054&sha=0957ea4e115236f885e360ac2dbca16ff2011411&name_0=PR&name_1=Upgrade%20check%20(amd_release)

Closes: #102331
Closes: #119212
Related: #114054

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 NO_SUCH_COLUMN_IN_TABLE exception Unexpected const virtual column: _table when a mutation (ALTER TABLE ... UPDATE/DELETE or lightweight DELETE) on a MergeTree table referenced the _table or _database virtual column. Mutations on Replicated tables that read a virtual column whose value may differ between replicas (_table, _database, _disk_name) are now rejected unless allow_nondeterministic_mutations is enabled, like non-deterministic functions. Closes #102331.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1252-master (included in 26.11 and later)

`MergeTreeSequentialSource` filled the constant virtual fields `_part_index`,
`_part_starting_offset` and `_sample_factor`, but not `_table` and `_database`,
which `ReadFromMergeTree` publishes for regular reads. A mutation referencing
either of them (`ALTER TABLE ... UPDATE v = _table`, `DELETE WHERE _table = ...`)
failed with `Unexpected const virtual column: _table` (`NO_SUCH_COLUMN_IN_TABLE`)
in `MutatePlainMergeTreeTask`.

Seen in the Upgrade check of #114054:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114054&sha=0957ea4e115236f885e360ac2dbca16ff2011411&name_0=PR&name_1=Upgrade%20check%20(amd_release)

Closes: #102331

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bbea07f]

Summary: ✅


AI Review

Summary

The PR supplies _table and _database during mutation reads and rejects replica-dependent virtual-column dependencies when replicated mutations are submitted. Both new stateless tests pass with the PR-head Fast test binary and match their references. No new inline findings were identified. The previously dismissed queued-mutation issue still reproduces and remains a correctness concern.

Findings

❌ Blockers

  • src/Interpreters/MutationsInterpreter.cpp:2700 — Validated dependencies can change before execution. [dismissed by author -- https://github.com/Provide _table and _database virtual columns to mutations #117724#discussion_r4363699840] The author deliberately deferred this as a pre-existing mutation-queue problem. It remains real because a mutation accepted with allow_nondeterministic_mutations = 0 can subsequently persist replica-local values: queue UPDATE value = a with merges stopped and a String ALIAS 'safe', change the definition to a String ALIAS _table, then resume merges. On the current PR binary, the completed mutation stores queue_r, its local table name. Execution obtains fresh metadata in MutateFromLogEntryTask and does not repeat this validation; differently named replicas can therefore compute different results and retain the first committed part. Preserve expanded dependencies in the queued command, or prevent/revalidate definition changes that introduce unsafe dependencies into pending mutations. The existing thread was left untouched.
Tests
  • ⚠️ Add a focused regression that queues a mutation, changes a referenced ALIAS definition, and resumes execution. It should prove that the validated dependency is preserved or the unsafe change is rejected; differently named replicas should retain identical, deterministic results.
Final Verdict

Status: ❌ Block — the dismissed queued-dependency correctness issue remains unresolved. The minimum required change is to preserve or revalidate those dependencies and cover the queue transition with a regression test. No additional inline comments were posted.

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

zlareb1 commented Sep 2, 2026

Copy link
Copy Markdown
Member

The values match ReadFromMergeTree exactly (ReadFromMergeTree.cpp:4862-4863), and after this change every declared MergeTree virtual is covered in the sequential-source path (via const_virtual_fields, getFieldForConstVirtualColumn, or the range reader's virtuals_to_fill), so no other column can hit the Unexpected const virtual column exception from a mutation.

One observation, below the bar for this PR but maybe worth a follow-up: _table and _database are declared with deterministic=false (MergeTreeData.cpp:877-878), yet the guard that rejects nondeterministic mutations on Replicated tables (MutationsInterpreter.cpp:2559-2574) only scans for nondeterministic functions, not for virtual columns flagged nondeterministic. Replicas of one ReplicatedMergeTree table can live under different local database/table names, so ALTER TABLE ... UPDATE v = _database (or DELETE WHERE _database = ...) now produces non-byte-identical parts across replicas; the checksum check in MutateFromLogEntryTask converts that into a first-finisher-wins fetch, so the persisted value (or whether the rows are deleted at all) depends on which replica commits first. The same already holds for _disk_name, which was reachable in mutations before this fix, so this is a pre-existing class — extending the determinism guard to consult the virtual column's deterministic flag would close it for all of them.

alexey-milovidov and others added 2 commits September 10, 2026 11:19
`04510_mutation_query_plan_only_virtual_columns` asserted that
`ALTER TABLE ... DELETE WHERE _table != ''` fails with `UNFINISHED`, because the
per-part read path could not materialize `_table`. This change makes that
mutation succeed, so the test now asserts the fixed behavior: the row is
deleted and one row remains.

For the same reason the `Unexpected const virtual column: _table: While
executing MergeTreeSequentialSource.` entry in the upgrade check error
allowlist (added in #117218 as a workaround for exactly this bug) is removed:
the pending mutation replayed after the upgrade now succeeds, so the message is
no longer produced, and keeping the entry would mask a regression of this fix.

The new test is renumbered to `05175_mutation_table_database_virtual_columns`,
the next free number after the merge with `master`.

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

Copy link
Copy Markdown
Member Author

🕵 Thanks for the careful read - and for confirming that no other declared MergeTree virtual can reach the Unexpected const virtual column throw from a mutation after this change.

I agree with the determinism observation and agree it is out of scope here: the guard in MutationsInterpreter::validateNonDeterministicMutationsForStorage only scans for nondeterministic functions and subqueries, so it misses every virtual column declared with deterministic=false - _disk_name, _part_index, _sample_factor were already reachable from mutations before this PR, and _table/_database join that set. Extending the guard to consult the virtual column's deterministic flag would change behavior for _disk_name mutations that are accepted today, so it belongs in its own change rather than in a bug fix. Filed as #119212 with your analysis.

Also in this push: merged master, and updated 04510_mutation_query_plan_only_virtual_columns, which pinned the unfixed behavior (DELETE WHERE _table != '' asserted to fail with UNFINISHED) - it now asserts the row is deleted. For the same reason the Unexpected const virtual column: _table entry that #117218 added to the upgrade-check error allowlist is removed: the pending mutation replayed after the upgrade now succeeds, so the message is not produced any more, and keeping the entry would mask a regression of this fix. The new test is renumbered to 05175_mutation_table_database_virtual_columns. Both tests pass locally.

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bbea07f3f with master bee6deac1 (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.

Object file sizes

7 object files changed (+39.59 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/MutationsInterpreter.cpp.o 954.50 KiB 984.51 KiB +30.01 KiB (+3.14%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -15.1 s (-5%) in total before that adjustment.

Job report

alexey-milovidov and others added 3 commits September 17, 2026 17:42
The number 05175 has been taken by many tests on master since the PR was opened.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… tables

`MutationsInterpreter::validateNonDeterministicMutationsForStorage` only
scanned for non-deterministic functions and subqueries, so a virtual column
declared with `deterministic = false` (`_table`, `_database`, `_disk_name`,
`_part_index`, ...) passed the guard. Replicas of one `ReplicatedMergeTree`
table may have different local names or disks, so such a mutation produced
different parts on different replicas and the persisted result depended on
which replica committed first (`checkPartChecksumsAndCommit` then fetched the
first finisher's part). Now that `_table` and `_database` are actually
provided to mutations, the guard reports them the same way as a
non-deterministic function, with `allow_nondeterministic_mutations` as the
escape hatch. A real column with the same name shadows the virtual one and is
not affected.

Addresses the review finding on
#117724 and
#119212.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI-review Blocker: mutations on Replicated tables that read a non-deterministic virtual column (_table, _database, _disk_name, ...) are now rejected with BAD_ARGUMENTS unless allow_nondeterministic_mutations = 1, the same contract as for non-deterministic functions; a real column shadowing the virtual one is unaffected. Test 05228_mutation_table_database_virtual_columns_replicated covers the rejection in ALTER UPDATE, ALTER DELETE and lightweight DELETE, the deterministic controls and the escape hatch, and the allow_nondeterministic_mutations doc string mentions the virtual columns. This also closes #119212.

Also merged master (the branch was 4085 commits behind) and renumbered the plain-MergeTree test to 05227_mutation_table_database_virtual_columns. Both new tests, 04510_mutation_query_plan_only_virtual_columns, 04873_running_concurrency_replicated_mutation, 01017_mutations_with_nondeterministic_functions_zookeeper and 05029_on_fly_mutation_sample_factor pass locally against the self-built binary. The previous red, Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel), was a job-level timeout after 2.5 hours with no failed test, so the fresh run will show whether it recurs.

alexey-milovidov and others added 2 commits September 24, 2026 00:34
…virtual-column

# Conflicts:
#	tests/docker_scripts/upgrade_runner.sh
…e replicated mutation guard

`findFirstNonDeterministicFunction` matched `ASTIdentifier::name`, the full compound text, so
`t._table` or `db.t._database` bypassed the check on `Replicated` tables. Identifiers qualified
with the mutated table's `StorageID` are now matched by their short name.

Lambda parameters named like a non-deterministic virtual column (`arrayExists(_table -> ...)`)
were falsely rejected. The lambda body is now visited with its parameters masked.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Avogar Avogar self-assigned this Sep 28, 2026
… in the replicated mutation guard

Lambda parameters are now tracked separately from the set of non-deterministic
virtual columns. Previously a parameter named `_table` removed `_table` from that
set, which also hid table-qualified references (`t._table`) inside the lambda body
and references inside the definitions of `ALIAS` columns. Now an identifier is
treated as bound to a parameter only when its first part names one. The
definition of an `ALIAS` / `EPHEMERAL` column is visited in the table scope, with
no lambda parameters bound. This also stops a parameter named like an `ALIAS`
column (`arrayExists(v -> v = 'x', [''])`) from being resolved as that column.

A subcolumn of an `ALIAS` column (`a.s` for `a Tuple(s String) ALIAS tuple(_table)`),
optionally qualified with the table, is now resolved to its parent column, and the
parent's definition is followed. Subcolumns of aliases are not registered in
`ColumnsDescription`, so they are looked up by prefix and checked against the type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… with the analyzer

The replicated mutation guard re-implemented identifier resolution on the AST
and kept missing ways to reach `_table` / `_database`: a bare `Nested` prefix
assembled from `ALIAS` subcolumns, and the table-qualified interpretation chosen
under `analyzer_compatibility_prefer_alias_over_subcolumn`.

Resolve the `UPDATE` / `DELETE` expressions with `QueryAnalyzer` against the
table instead, the same way the mutation is executed, and refuse the mutation
when any non-deterministic virtual column is read from the table, also through
`ALIAS` definitions. `EPHEMERAL` definitions, which the analyzer does not
expand, are resolved in turn. Since the mutation may run in the background with
a different value of `analyzer_compatibility_prefer_alias_over_subcolumn`, both
interpretations are checked.

`_part_index` and `_part_starting_offset` are always 0 in a mutation, which
reads every part on its own, so they are allowed like `_sample_factor`.

`findFirstNonDeterministicFunction` is back to its version on `master`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 18, 2026 06:23
…nly the used qualifier interpretations

`findNonDeterministicVirtualColumn` resolved the expressions of all commands in one `ASTExpressionList`,
so an alias defined in a later command (`UPDATE value = ('safe' AS _table)`) could hide a read of the
`_table` virtual column in an earlier command. Each command, and each followed `EPHEMERAL` definition,
is now resolved in its own scope, the same way the commands are analyzed in separate stages on execution.

The check also resolved compound identifiers under both values of
`analyzer_compatibility_prefer_alias_over_subcolumn`, which made deterministic mutations fail when the
unused interpretation was ill-typed. Now only the value of the query and the value of the background
context, which executes the mutation, are checked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in the replicated mutation guard

A bare identifier that is both an alias and a column, such as `_table` in
`UPDATE value = ('safe' AS _table) WHERE _table != ''`, is resolved differently
depending on `prefer_column_name_to_alias`. The mutation is validated with the
settings of the query but executed with the settings of the background context,
so `findNonDeterministicVirtualColumn` now analyzes the expressions with the
name-resolution settings (`analyzer_compatibility_prefer_alias_over_subcolumn`
and `prefer_column_name_to_alias`) of both contexts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in the replicated mutation guard

`MATERIALIZE COLUMN` of an `EPHEMERAL` column defined over `_database` or `_table` evaluates the
column's default expression inside the mutation, so each replica would write its own local name into
the new part. Treat the default expression of the materialized column as one more scope of the guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits October 27, 2026 10:08
…g non-deterministic virtual columns

A mutation calculates projections from the block read by `MergeTreeSequentialSource`, which now carries
`_table` and `_database`, so `MATERIALIZE PROJECTION` (or any mutation rebuilding a projection) for a
projection reading such a column would store different data on differently named replicas. Which
projections are rebuilt depends on the state of each part, so every projection is checked unless the
mutation only drops projections.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ojections reading non-deterministic virtual columns

`MODIFY COLUMN` and other schema changes on a `ReplicatedMergeTree` table go through
`StorageReplicatedMergeTree::alter`, which queues the generated mutation without the
check of `validateNonDeterministicMutationsForStorage`. Such a mutation rebuilds the
projections sorted by a column whose type changes, so a projection reading `_table`
could store different data on differently named replicas. Run
`MutationsInterpreter::findNonDeterministicVirtualColumn` on the generated mutation
commands before any local state is changed, unless `allow_nondeterministic_mutations`
is enabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits October 29, 2026 03:09
…TER` metadata

`StorageReplicatedMergeTree::alter` checked the mutation generated by a schema change against the
current metadata, so it missed a projection reading `_table` added by the same `ALTER` (which the
mutation then rebuilds), and refused `DROP PROJECTION p, MODIFY COLUMN ...`, because the generated
`DROP_PROJECTION` command stores the projection name in `column_name`. Now
`MutationsInterpreter::findNonDeterministicVirtualColumn` accepts the metadata the mutation will be
executed with, and the `ALTER` passes `future_metadata`, which includes added projections and
excludes dropped ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Avogar
Avogar added this pull request to the merge queue Nov 3, 2026
Merged via the queue into master with commit 1a9d1de Nov 3, 2026
180 checks passed
@Avogar
Avogar deleted the fix/mutation-table-virtual-column branch November 3, 2026 20:57
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026
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

5 participants