Repository navigation
Supply _sample_factor to the per-part read path used by mutations and merges - #109813
alexey-milovidov merged 21 commits into
Conversation
A mutation referencing _sample_factor, _table or _database (e.g. DELETE FROM t WHERE _sample_factor > 0.1) parsed and started running, then failed mid-execution in MergeTreeSequentialSource with "Unexpected const virtual column" (NO_SUCH_COLUMN_IN_TABLE). These three virtuals get their value from the query plan (ReadFromMergeTree fills them into shared_virtual_fields); the mutation/merge read path cannot produce them. Reject such references during mutation analysis instead, so the query fails up front. A physical column that happens to share the name is left untouched. Closes ClickHouse#78465 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-13:20260708-143700 |
|
cc @CurtizJ @Michicosun — could you review this? It fixes #78465: a mutation referencing |
|
Workflow [PR], commit [1b8c928] Summary: ✅
AI ReviewSummaryThis PR replaces the earlier analysis-time guard with a reader-side fix: Findings❌ Blockers
Final Verdict❌ Changes requested until the on-the-fly mutation path binds |
Address the review: the previous gate matched raw ASTIdentifier names, which broke in both directions. It falsely rejected higher-order expressions whose lambda parameter is named _table/_database/_sample_factor, and it missed qualified references (t._sample_factor) whose name() is the compound identifier. The check now walks the mutation expressions (WHERE predicate and UPDATE assignment right-hand sides) with column-usage semantics: it matches the identifier short name so qualified references are caught, treats a compound whose leading part is a real column as a subcolumn access, shadows lambda formal parameters over the lambda body, and does not descend into subqueries (which are evaluated as their own SELECT and can materialize these virtuals). Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed the raw-`ASTIdentifier` walk. The check no longer matches identifier names verbatim; it walks the mutation expressions (WHERE predicate + UPDATE assignment RHS) with column-usage semantics:
Verified on both analyzers (`allow_experimental_analyzer` 0/1): lambda params |
…the mutation virtual-column gate The previous fast path exempted a compound identifier when only its first name part matched a real column. When a table name collides with a column (table t with a column t), t._table has a leading real column yet the resolvers strip the table qualifier and bind it to the virtual _table, so the reference slipped past the gate and failed mid-mutation with 'Unexpected const virtual column'. Now a compound is exempted only if some qualifier-stripped suffix (t.tup._table -> tup._table -> ...) resolves to a real column or subcolumn via hasColumnOrSubcolumn; otherwise the query-plan-only virtual is rejected at analysis. Genuine Tuple subcolumns (tup._table) and shadowing physical columns are still allowed; lambda params and subqueries are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Good catch, fixed in 68b4c60. The old fast path exempted a compound when only its first name part matched a real column ( Now the compound is exempted only if some qualifier-stripped suffix resolves to a real column or subcolumn via Verified both directions on both analyzers (
Added the two regression cases to |
CI finish ledger — 68b4c60Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
The merged family-2310 fix (#106647, 2026-06-19) is already an ancestor of this branch and does not cover this Session id: cron:our-pr-ci-monitor:20260709-040000 |
|
Fixing PR for the AST fuzzer LOGICAL_ERROR |
CI finish ledger — 68b4c60CI fully finished (Finish Workflow passed; last check 2026-07-09T03:49:02Z). Every failure has an owner.
Session id: cron:our-pr-ci-monitor:20260709-060000 |
…only virtuals The mutation-analysis guard walked the mutation expressions and keyed on the identifier's short name, so it treated a declared ALIAS column as a real column and stopped there. But an ALIAS column is replaced by its defining expression only later, in QueryAnalyzer (ColumnDefaultKind::Alias, QueryAnalyzer.cpp:4407), i.e. after this check has already passed. An alias over `_table` or `_database` therefore reached the mutation read path and still failed mid-execution with "Unexpected const virtual column", which is exactly the failure the guard exists to turn into an up-front analysis error. Follow the alias expression during the walk, tracking the names currently being expanded so a self-referential alias cannot loop. Only `_table` and `_database` are reachable this way: aliasing any part-derived virtual (`_part`, `_sample_factor`, ...) is already rejected when the table is created, and on the old analyzer an alias over a virtual does not resolve at all. Reported by the automated reviewer on ClickHouse#109813. The reviewer also flagged SQL UDF inlining as a second carrier; that one does not apply, because for an ALTER mutation the UDFs are inlined in InterpreterAlterQuery::executeToTable (InterpreterAlterQuery.cpp:418-419) before the mutation commands are run (:498 -> :352), so the guard already sees the expanded body. Co-Authored-By: Claude Fable 5 <[email protected]>
Following the alias by the identifier's short name ran before the compound suffix check, so a `Tuple` subcolumn whose field name collides with an `ALIAS` column was mistaken for that alias. On a table with `tup Tuple(a_tbl String)` and `a_tbl String ALIAS _table`, the valid predicate `tup.a_tbl = 'missing'` was rejected as a reference to `_table`. The compound suffix check already distinguishes a real column or subcolumn access from the bare short name, so run it first: a compound that resolves to a real column or subcolumn is neither the virtual nor the alias. Also wrap literal class, function and log-message names in the surrounding comment in inline code, and refer to a method as `name` rather than `name()`. Co-Authored-By: Claude Fable 5 <[email protected]>
Per the repository convention, literal SQL keywords and class, function and log-message names in comments belong in inline code blocks. Co-Authored-By: Claude Fable 5 <[email protected]>
The rationale belongs in the commit message and the pull request description, not repeated in the code. Co-Authored-By: Claude Fable 5 <[email protected]>
Only the analyzer resolves an `ALIAS` column defined over a virtual column; with `allow_experimental_analyzer = 0` even creating the fixture fails with `UNKNOWN_IDENTIFIER`, so the whole test failed under the old analyzer. Pin the setting around those cases and restore it afterwards, leaving the rest of the test to run under both analyzers. Co-Authored-By: Claude Fable 5 <[email protected]>
CI finish ledger — d10adb5Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260729-103000 |
The `ALIAS`-over-virtual cases of 04510 cannot run under the old analyzer at all: only the analyzer resolves an `ALIAS` column defined over a virtual column, so even creating the fixture fails with `UNKNOWN_IDENTIFIER`, and a mutation over an `ALIAS` column fails with `Missing columns` regardless of whether any virtual is involved. The previous attempt pinned the setting with a session `SET allow_experimental_analyzer = 1`, which cannot work here. A mutation is executed by the background pool, and `MutatePlainMergeTreeTask` builds its context from `Context::getBackgroundContext` rather than from the client session, so the mutation always observes the server default. The `CREATE` succeeded under the pin while the mutation that followed still failed. Move those cases to their own test tagged `no-old-analyzer`, which the runner resolves by probing the server's own setting and therefore also covers the `compatibility` randomization route. The rejection gate itself is a plain AST walk in `MutationsInterpreter::prepare` and is analyzer-independent, so the core cases stay in 04510 and keep running on both analyzers. Co-Authored-By: Claude Fable 5 <[email protected]>
Two gaps found while reviewing the gate. A lightweight update is also built through `MutationsInterpreter`, but it reads through `ReadFromMergeTree`, which does supply `_sample_factor`, `_table` and `_database`. Rejecting those references there turned a working `UPDATE ... SET v = length(_table)` into `NO_SUCH_COLUMN_IN_TABLE`. Only the per-part path reads through `MergeTreeSequentialSource`, so key the gate on `return_mutated_rows` being unset, which is what already distinguishes the two readers elsewhere in this file. An `ALIAS` column may also be named like one of the guarded virtuals while being defined over another one (`_table String ALIAS _database`). Alias expansion was skipped whenever the alias short name was itself guarded, so the reference reached the read path and failed mid-execution with `Unexpected const virtual column: _database` - the failure this gate exists to prevent. Inspect an alias definition whatever the alias is called. Both cases are now covered by tests. Co-Authored-By: Claude Fable 5 <[email protected]>
…fines Two more shapes the walk mistook for a reference to a guarded virtual column, both of which mutate fine on master. A member access rooted at a lambda parameter is an element of that parameter: in `arrayMap(x -> x._table, arr)` the short name of `x._table` is `_table`, but only the bare parameter name was shadowed. Treat a compound whose leading part is shadowed as belonging to that name. An expression alias defines its name for the whole expression it appears in, not just for the subtree below it, so `(1 AS _table) + _table` refers to the alias. Collect the aliases of an expression before walking it and shadow them for the entire walk. Both cases are now covered by tests. Co-Authored-By: Claude Fable 5 <[email protected]>
A subquery is resolved in its own scope, so collecting its aliases along with the enclosing expression's let `... WHERE _table != '' AND c0 IN (SELECT 1 AS _table)` pass the gate and fail mid-execution with `Unexpected const virtual column`. Stop collecting at a subquery boundary, matching the walk that does the rejection. Co-Authored-By: Claude Fable 5 <[email protected]>
One `UPDATE` assignment may refer to an alias that another one defines, as in `UPDATE v = (1 AS _table), w = _table`, which mutates fine on master. Collecting the aliases per assignment rejected the second one, so collect them across the predicate and all assignments before rejecting anything. Co-Authored-By: Claude Fable 5 <[email protected]>
The motivation belongs in the commit messages, not repeated at each site. Co-Authored-By: Claude Fable 5 <[email protected]>
`mutations_sync = 2` reports a mutation that failed in the background with the same error code as an up-front rejection, so an error assertion alone does not distinguish them. Check `system.mutations` for failed entries as well. Co-Authored-By: Claude Fable 5 <[email protected]>
The gate follows an `ALIAS` column to its defining expression, but walked that expression with only the enclosing command's aliases. An alias the definition itself declares was therefore invisible, so a column defined as `((1 AS _table) + _table)` was read as referencing the virtual column and its mutation was rejected although master runs it. That expression is its own scope, so collect its aliases before walking it, the same way a mutation command's aliases are collected. Also assert in the alias test that the four rejected mutations left no entry in `system.mutations`, which pins that they were rejected before being queued rather than failing later in the background.
The scoping rationale and the resolver evidence for it belong in the commit messages of the two preceding commits, not beside the code.
CI finish ledger - c28fff8CI is fully finished on this head and there is nothing to own: 174 check-runs, all completed, 0 failures (156 success, 18 skipped), with both This head clears the one PR-caused row from the previous ledger ( Session id: cron:our-pr-ci-monitor:20260730-020000 |
Michicosun
left a comment
There was a problem hiding this comment.
reduce diff, remove all comments, make tests simpler, do not mix multiple cases in a single test, write single test file.
_sample_factor is an Ephemeral MergeTree virtual column registered with VirtualsMaterializationPlace::Reader, so a reader is expected to supply its value. ReadFromMergeTree::initializePipeline publishes it into shared_virtual_fields and MergeTreeReadPoolBase copies that map into every read task, which is why SELECT resolves it. The per-part path used by mutations and merges did not: createMergeTreeSequentialSource seeded only _part_index and _part_starting_offset, so IMergeTreeReader::fillVirtualColumns found nothing in virtual_fields, fell through to getFieldForConstVirtualColumn and threw "Unexpected const virtual column: _sample_factor". A mutation referencing it therefore started, failed per part with UNFINISHED wrapping NO_SUCH_COLUMN_IN_TABLE, and left the mutation entry stuck. One read path was omitting what its sibling copies wholesale. Seed the field where the sibling already does. A mutation reads a part whole, so the value is 1: used_sample_factor is declared 1.0 and is overwritten only for an actual SAMPLE clause, which a mutation predicate cannot carry, and an unsampled SELECT of the same table returns 1 on master. It is a literal constant, identical on every replica, so it is safe on ReplicatedMergeTree and SharedMergeTree. LazyReadFromMergeTreeSource already publishes it the same way. This replaces the analysis-time rejection this branch previously carried. That guard decided column identity from raw AST identifier names plus ColumnsDescription lookups, which cannot distinguish an ALIAS over a virtual column from an ALIAS over a real Tuple: ColumnsDescription deliberately skips addSubcolumns for ColumnDefaultKind::Alias, so hasColumnOrSubcolumn is false by construction for any alias. Six holes were measured on the published head in both directions, and one of them rejected "a Tuple(_table UInt8) ALIAS tup" over a real tup, which master and released 26.7.2 both accept. Deleting the guard removes that regression and drops 193 lines; isQueryPlanOnlyVirtualColumn loses its last caller and goes with it. Scope is _sample_factor, which is what issue 78465 reports. _table and _database derive from the local storage id and a mutation persists what it reads, so seeding them could diverge replicas, while rejecting them for every MergeTree would be a new restriction because a non-replicated table has only one name. That belongs in the admission check that runs even when validate_mutation_query is 0, and is filed separately; their current mid-execution failure is unchanged here and the test keeps a row documenting it. The two test files collapse into one, per review. The test asserts the materialized value rather than only the absence of an exception, because seeding a wrong constant still succeeds and is caught only by the value. Three statements pin analyzer settings: two shapes bind only under the analyzer, and the pre-existing real-column-override failure is raised during analyzer-driven mutation validation and disappears when either enable_analyzer or validate_mutation_query is off. Every other row was measured to behave identically on both analyzers, so the file needs no analyzer tag and the old-analyzer lanes keep full coverage.
Drop the two rows whose per-statement `SETTINGS enable_analyzer = 1` cannot reach mutation execution. A mutation runs in the background task context, which `MutatePlainMergeTreeTask::createTaskContext` builds from the server background context, and `MergeTreeMutationEntry` persists no settings, so a statement-level pin only ever reaches validation. On the two dedicated old-analyzer stateless lanes the background context therefore takes `allow_experimental_analyzer` from the `default` profile that `tests/config/users.d/analyzer.xml` sets to 0. Measured with that exact profile installed on a local server: the alias subcolumn row fails with `NOT_FOUND_COLUMN_IN_BLOCK` because `a._table` must be resolved through the alias expression while the part is read. The expression alias row passes, since its alias is fully resolved during validation, so only one of the two rows was the live exposure; both are removed because both pin the behaviour of the raw AST guard this branch deletes rather than the seeded value, and neither mentions `_sample_factor`. Make the `SELECT` control real. It sat after the two `DELETE` rows had emptied the table, so it returned no rows and asserted nothing, and had it returned a row `_database` would have made it non-deterministic. It now runs straight after the `INSERT` and reads `_sample_factor` alone, which checks the seeded constant against what `ReadFromMergeTree` publishes on the `SELECT` path. Correct the seed comment. `ReadFromPart::initializePipeline` prunes marks from the primary key and `WhatIfEmpiricalEstimator` passes an explicit mark range, so this path does not always read a whole part. The value is 1 because `used_sample_factor` is only ever overwritten under sampling.
_sample_factor to the per-part read path used by mutations and merges
Internal second-model review (click to expand)Two review rounds ran on this redesign: an independent cold review of the resulting code plus a ❌ Round 1 blocker, fixed: a per-statement analyzer pin cannot reach mutation executionTwo test rows carried Both parties converged on this mechanism independently, and it was reproduced on a server carrying Both rows are now deleted. Neither mentioned
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-11:20260731-033001 |
Internal second-model review (click to expand)Two review rounds ran on this redesign: an independent cold review of the resulting code plus a ❌ Round 1 blocker, fixed: a per-statement analyzer pin cannot reach mutation executionTwo test rows carried Both parties converged on this mechanism independently, and it was reproduced on a server carrying Both rows are now deleted. Neither mentioned
|
|
Thanks, that pushed me to the right layer. I dropped the analysis-time guard entirely and fixed the read path instead, so all four points are addressed:
The reason Two things I deliberately left out of scope, both filed separately: |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code |
CI finish ledger - 1b8c928CI is fully finished on this head with no failing checks: all 174 check-runs completed,
Session id: cron:our-pr-ci-monitor:20260804-043000 |
|
Hi — this looks like a backport candidate for |
|
@groeneai @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
Confirmed as a backport candidate for all five, with two caveats worth recording before the label goes on. Reproduction, independently measured. Official per-branch binaries from
The cherry-pick is clean and lands the whole fix. Caveat 1: one label, not five. Caveat 2: the test file does not port below 26.6. Two of its
Both settings exist on all five, so this is real behavioural drift rather than a missing setting, and the portable arms pass everywhere. Expect the 25.8/26.3/26.5 backport PRs to need those two arms adjusted by hand. On #115837, which you filed alongside this: it does not block the backport, and it is not an incompleteness introduced here. I ran its own carrier against the five release binaries that do not contain this fix: Identical with and without the fix, so the on-the-fly divergence is already on every one of those branches. This PR fixed the materialized arm and never touched the on-the-fly one, which is what my review round measured before merge too. Backporting therefore removes the |
With a pending mutation whose expression references _sample_factor, reading under apply_mutations_on_fly = 1 plus a SAMPLE clause evaluated the expression with the reading query's sample factor instead of the value the background materialization persists, so the preview disagreed with the eventual materialized state. A pending ALTER TABLE t DELETE WHERE _sample_factor > 1 made the predicate true for every row, so a SAMPLE read returned no rows. ReadFromMergeTree::initializePipeline publishes the query's factor into shared_virtual_fields, and MergeTreeReadPoolBase::buildReadTaskInfo copies that map wholesale into the read task after building the pending-mutation steps. One map therefore serves two consumers that need different values in the same query: the query's own _sample_factor, which must keep the query's factor, and the mutation expression, which must see what the background mutation sees (1, seeded in createMergeTreeSequentialSource). Pinning the shared map would clamp both and turn a wrong-mutation-value bug into a wrong-query-value one, so the binding has to be per consumer. AlterConversions::getMutationSteps now rebinds _sample_factor to 1 for the mutation step's expression dependencies only, through a new ActionsDAG member substituteInputForConsumersOnly. It rewires the consumer edges of an input to a constant while leaving the input node and the outputs untouched, so the passthrough column the step forwards to the query still carries the query's factor. ActionsDAG::substitute is deliberately not reused: it converts the matched node in place to a COLUMN, which would replace that passthrough too. The rebinding is guarded by isVirtualColumn so a real physical column of that name is not folded to a constant. This is the read-path counterpart of ClickHouse#109813, which fixed the background arm. _table and _database are published by the adjacent lines but are left alone: their background arm fails outright, so no eventual value exists to match, and choosing one is a replica-locality design decision. The new test's oracle is a pair of assertions in one row, the previewed value being 1 while the same query's _sample_factor is still 2, because asserting only the first would also pass if the query's own value were clamped. Closes: ClickHouse#115837
|
Gentle ping on the one open item here: @alexey-milovidov, could you apply |
Closes: #78465
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a mutation that references the
_sample_factorvirtual column failing mid-execution withUnexpected const virtual column: _sample_factorand leaving the mutation stuck. A mutation now reads it as1, the same value a query withoutSAMPLEreturns.Description
_sample_factoris registered withVirtualsMaterializationPlace::Reader, so a reader is expected to supply its value.ReadFromMergeTreepublishes it intoshared_virtual_fieldsand the normal read pool copies that map into every read task, which is whySELECTresolves it. The per-part path used by mutations and merges does not:createMergeTreeSequentialSourceseeds only_part_indexand_part_starting_offset, sofillVirtualColumnsfalls through to a throw.ALTER TABLE t UPDATE u = _sample_factor WHERE ...therefore starts, then fails per part withCode 341wrappingCode 16, and the mutation entry stays stuck.The fix seeds the field where the sibling already does. The value is
1because noSAMPLEclause reaches this path:used_sample_factoris declared1.0and is overwritten only for an actualSAMPLEclause, which a mutation predicate cannot carry. It is a literal constant, identical on every replica, so it is safe on ReplicatedMergeTree and SharedMergeTree. The net change against master is 3 lines of source plus one test.This replaces the analysis-time rejection this PR previously carried, so the guard it added earlier is gone and
MutationsInterpreter.cppis now untouched. That guard decided column identity from raw AST identifier names, which cannot distinguish anALIASover a virtual column from anALIASover a realTuple, becauseColumnsDescriptiondeliberately omits alias subcolumns. One of the six holes measured rejecteda Tuple(_table UInt8) ALIAS tupover a realtup, which master and 26.7.2 both accept, so dropping the guard also removes that regression.Scope is
_sample_factoronly, which is what the issue reports._tableand_databasederive from the local storage id, and a mutation persists what it reads, so seeding them could diverge replicas, while rejecting them for every MergeTree would be a new restriction. That design is filed separately, and their current mid-execution failure is unchanged here.