Skip to content

Supply _sample_factor to the per-part read path used by mutations and merges - #109813

Merged
alexey-milovidov merged 21 commits into
ClickHouse:masterfrom
groeneai:fix-78465-sample-factor-mutation
Aug 21, 2026
Merged

alexey-milovidov merged 21 commits into
ClickHouse:masterfrom
groeneai:fix-78465-sample-factor-mutation

Conversation

@groeneai

@groeneai groeneai commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #78465

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):

Fixes a mutation that references the _sample_factor virtual column failing mid-execution with Unexpected const virtual column: _sample_factor and leaving the mutation stuck. A mutation now reads it as 1, the same value a query without SAMPLE returns.

Description

_sample_factor is registered with VirtualsMaterializationPlace::Reader, so a reader is expected to supply its value. ReadFromMergeTree publishes it into shared_virtual_fields and the normal read pool copies that map into every read task, which is why SELECT resolves it. The per-part path used by mutations and merges does not: createMergeTreeSequentialSource seeds only _part_index and _part_starting_offset, so fillVirtualColumns falls through to a throw. ALTER TABLE t UPDATE u = _sample_factor WHERE ... therefore starts, then fails per part with Code 341 wrapping Code 16, and the mutation entry stays stuck.

The fix seeds the field where the sibling already does. The value is 1 because no SAMPLE clause reaches this path: used_sample_factor is declared 1.0 and is overwritten only for an actual SAMPLE clause, 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.cpp is now untouched. That guard decided column identity from raw AST identifier names, which cannot distinguish an ALIAS over a virtual column from an ALIAS over a real Tuple, because ColumnsDescription deliberately omits alias subcolumns. One of the six holes measured rejected a Tuple(_table UInt8) ALIAS tup over a real tup, which master and 26.7.2 both accept, so dropping the guard also removes that regression.

Scope is _sample_factor only, which is what the issue 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. That design is filed separately, and their current mid-execution failure is unchanged here.

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]>
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (c0 UInt32) ENGINE=MergeTree ORDER BY c0 SAMPLE BY c0; INSERT INTO t VALUES (1),(2),(3); DELETE FROM t WHERE _sample_factor > 0.1; fails every time on master with Code: 16 Unexpected const virtual column: _sample_factor (NO_SUCH_COLUMN_IN_TABLE). Same for _table / _database and for ALTER ... UPDATE.
b Root cause explained? _sample_factor, _table, _database get their value from the query plan (ReadFromMergeTree fills them into shared_virtual_fields), so they only exist inside a SELECT plan. MutationsInterpreter collects available virtuals with VirtualsMaterializationPlace::All, so a mutation referencing them passes analysis; then the mutation/merge read path (MergeTreeSequentialSource -> IMergeTreeReader::fillVirtualColumns -> getFieldForConstVirtualColumn) cannot produce the value and throws mid-execution.
c Fix matches root cause? Yes. It rejects exactly the query-plan-only virtuals during mutation analysis (MutationsInterpreter::prepare, MergeTree sources), turning the mid-execution failure into an up-front analysis error, which is the behavior the issue asks for.
d Test intent preserved / new tests added? New test 04510_mutation_query_plan_only_virtual_columns added: asserts the three virtuals are rejected in DELETE/UPDATE with NO_SUCH_COLUMN_IN_TABLE, that SELECT of them still works, and that a materializable virtual (_part) still works in a mutation.
e Both directions demonstrated? Yes. Without the fix the repro fails mid-mutation; with the fix it fails at analysis time (test passes). Verified via clickhouse-local and a real server with mutations_sync=2, both analyzers.
f Fix is general across code paths? Yes. The check walks the full mutation command AST (predicate + update assignments) for all command types, and the query-plan-only set is defined in one helper (isQueryPlanOnlyVirtualColumn) covering exactly the virtuals ReadFromMergeTree fills into shared_virtual_fields. Other virtuals the reader can materialize (_part, _partition_id, _part_offset, _distance, ...) are unaffected.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The rejection is by column name, independent of the surrounding expression, function wrapping, or datatype; it fires whether the virtual is used bare or inside a function. A physical column sharing the name (columns.has(name) true) is explicitly left alone, so no datatype/wrapper case regresses.
h Backward compatible? (maintainer-approved exception only) Yes, fully compatible. The rejected queries never worked (they failed at execution); this only moves the failure earlier. No setting default, on-disk/wire format, or existing-data validation changes. A physical column named _sample_factor/_table/_database keeps its prior behavior.
i Invariants and contracts preserved? Yes. The change adds an analysis-time guard before any stage building; it does not touch the read path, block structure, or mutation execution. MutationsInterpreter's existing virtual-column handling and column-order invariants are untouched.

Session id: cron:clickhouse-worker-slot-13:20260708-143700

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @Michicosun — could you review this? It fixes #78465: a mutation referencing _sample_factor/_table/_database (values only produced by the query plan) was accepted at analysis time and then failed mid-execution in MergeTreeSequentialSource. This rejects those query-plan-only virtual columns during mutation analysis so the query fails up front, leaving physical columns of the same name and all reader-materializable virtuals untouched.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1b8c928]

Summary: ✅


AI Review

Summary

This PR replaces the earlier analysis-time guard with a reader-side fix: createMergeTreeSequentialSource now seeds _sample_factor as 1, so background mutations no longer get stuck with Unexpected const virtual column. The patch is small and targets the confirmed omission, but it still leaves one correctness hole on the supported read surface: pending on-the-fly mutation replay can evaluate the same mutation with a different _sample_factor than the value this PR persists.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeSequentialSource.cpp:333] [dismissed by author -- https://github.com/Supply _sample_factor to the per-part read path used by mutations and merges #109813#issuecomment-5139237872] This PR makes _sample_factor mutations succeed in the background path by hardcoding _sample_factor = 1, but apply_mutations_on_fly = 1 still replays the same pending mutation through the normal ReadFromMergeTree pipeline, which fills _sample_factor from the querying SAMPLE clause (src/Processors/QueryPlan/ReadFromMergeTree.cpp:4128, src/Storages/MergeTree/MergeTreeReadPoolBase.cpp:240-278, src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp:542). A sampled SELECT can therefore preview a different UPDATE/DELETE result than the value this PR later materializes, so the mutation’s meaning still depends on the reader’s sampling ratio instead of only on the mutation itself. Because this change turns _sample_factor mutations from stuck failures into supported mutations, that mismatch is part of the impacted surface, not a separate out-of-scope pre-existing bug.
Final Verdict

❌ Changes requested until the on-the-fly mutation path binds _sample_factor to the same value as background materialization, or sampled preview of these mutations is explicitly rejected.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 8, 2026
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]>
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

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:

  • short-name match so a qualified reference like `t._sample_factor` is caught (previously missed: `name()` was the compound identifier);
  • a compound whose leading part is a real column (`tuple_col._table`) is treated as subcolumn access and left alone;
  • lambda formal parameters are shadowed over the lambda body, so `arrayMap(_table -> _table + 1, arr)` is accepted (previously falsely rejected);
  • subqueries are not descended into (their read path is a SELECT that can materialize these virtuals).

Verified on both analyzers (`allow_experimental_analyzer` 0/1): lambda params _table/_sample_factor accepted; qualified t._sample_factor rejected at analysis (Code 16); unqualified _sample_factor/_table/_database in WHERE and UPDATE RHS rejected; plain _part DELETE, subquery _sample_factor, and qualified real-column mutations unaffected. Regression test 04510 extended with the lambda-param and qualified-reference cases; it fails on the previous commit and passes now (10/10).

…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]>
@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch, fixed in 68b4c60.

The old fast path exempted a compound when only its first name part matched a real column (columns.has(name_parts.front())). That is exactly the bypass: with a table whose name collides with a column (CREATE TABLE t (t UInt8) ...), t._table has a leading real column t, so it was exempted, then both resolvers stripped the t. qualifier and bound it to the virtual _table — reaching Unexpected const virtual column mid-mutation.

Now the compound is exempted only if some qualifier-stripped suffix resolves to a real column or subcolumn via ColumnsDescription::hasColumnOrSubcolumn(GetColumnsOptions::All, suffix) — the whole name (tup._table, a Tuple subcolumn), the name after dropping a table/db qualifier (t.tup._table -> tup._table), or the short name (a physical column shadowing the virtual). Otherwise the query-plan-only virtual is rejected at analysis. Lambda-param shadowing and subquery skipping are unchanged.

Verified both directions on both analyzers (allow_experimental_analyzer 0 and 1):

  • CREATE TABLE t (t UInt8) ENGINE=MergeTree ORDER BY t; ALTER TABLE t DELETE WHERE t._table != '' — rejected at analysis with the fix; on the prior build it slipped the gate (new analyzer) / hit a late Missing columns (old analyzer).
  • genuine Tuple(_table UInt32, _sample_factor Float64) subcolumn access tup._table / tup._sample_factor — still allowed.
  • All existing cases (unqualified, tbl._sample_factor, UPDATE RHS, lambda params, subquery, plain _part) unchanged.

Added the two regression cases to 04510_mutation_query_plan_only_virtual_columns (collide-name rejected; real Tuple subcolumn allowed).

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 68b4c60

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Trying to get name of not a column: ExpressionList (STID 2310-3e66) crash (LOGICAL_ERROR on EXPLAIN PIPELINE SELECT ... APPLY lambda ... viewExplain(...)) — NOT PR-caused (this PR's diff is mutation-analysis-only; the fuzzer mutated a SELECT and hit a pre-existing engine bug) a fix task is created (investigating at full effort — fixing-PR link to follow here)
Mergeable Check rollup of the AST fuzzer red above same owner
CH Inc sync — CH Inc sync (private, not actionable by us)

The merged family-2310 fix (#106647, 2026-06-19) is already an ancestor of this branch and does not cover this ExpressionList / EXPLAIN-of-EXPLAIN sub-shape (fresh STID 2310-3e66), so it is not linked as the owner.

Session id: cron:our-pr-ci-monitor:20260709-040000

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer LOGICAL_ERROR Trying to get name of not a column: ExpressionList (STID 2310-3e66) surfaced on this PR: #109862. It is a pre-existing trunk bug (GROUP BY GROUPING SETS + force_aggregation_in_order on the old analyzer), not caused by this PR's changes.

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 68b4c60

CI fully finished (Finish Workflow passed; last check 2026-07-09T03:49:02Z). Every failure has an owner.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Logical error: Trying to get name of not a column: ExpressionList (STID 2310-3e66) trunk fuzzer LOGICAL_ERROR (family-2310) a fix task is created (investigating at full effort — fixing-PR link to follow here). NOT PR-caused: the offending fuzzed query is EXPLAIN PIPELINE SELECT ... viewExplain ... enable_sharding_aggregator=1 over test_sharded_agg_neg__fuzz tables — no mutation / _sample_factor path; this PR's diff (MutationsInterpreter.cpp, MergeTreeVirtualColumns.*) cannot affect EXPLAIN PIPELINE SELECT analysis. Chronic trunk: 59 hits / 45 unrelated PRs / 30d.
Mergeable Check / PR rollup of the AST fuzzer job above same owner
CH Inc sync — CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260709-060000

groeneai and others added 5 commits July 29, 2026 03:27
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d10adb5

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 1/3) / 04510_mutation_query_plan_only_virtual_columns PR-caused — this PR's own new test, failing 3/3 on the OLD analyzer with Code: 341 ... Code: 47 Missing columns: 'a_real' ... (UNKNOWN_IDENTIFIER) mid-mutation. The test carries neither a session SET enable_analyzer = 1 nor a no-old-analyzer tag, so it runs on a configuration the fix does not cover PR-caused → fixed in this PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky, trunk — under parallel replicas one statement becomes several reads of the same table on this server with different query ids, so the holder query competes against itself for the single max_concurrent_queries slot #112385 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-103000

groeneai and others added 7 commits July 29, 2026 12:34
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]>
groeneai added 2 commits July 29, 2026 21:12
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c28fff8

CI 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 Config Workflow and Finish Workflow green. CIDB returns no FAIL or ERROR row for this commit either.

This head clears the one PR-caused row from the previous ledger (d10adb548122): 04510_mutation_query_plan_only_virtual_columns was failing 3/3 on the old-analyzer job, and it now passes on every job on this head.

Session id: cron:our-pr-ci-monitor:20260730-020000

@Michicosun Michicosun left a comment

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.

reduce diff, remove all comments, make tests simpler, do not mix multiple cases in a single test, write single test file.

groeneai added 2 commits July 31, 2026 01:40
_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.
@groeneai groeneai changed the title Reject query-plan-only virtual columns in mutations at analysis time Supply _sample_factor to the per-part read path used by mutations and merges Jul 31, 2026
@groeneai

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

Two review rounds ran on this redesign: an independent cold review of the resulting code plus a
separate second-model pass, adjudicated against the recorded evidence. Round 1 found a blocker and
bounced; this round is clean. 3 findings adjudicated: 2 AGREE (both fixed), 1 DISAGREE with
measurements.

❌ Round 1 blocker, fixed: a per-statement analyzer pin cannot reach mutation execution

Two test rows carried SETTINGS enable_analyzer = 1 so they would behave the same on the two
dedicated old-analyzer lanes. That pin reaches the client and validation context only. A mutation
executes in a background task context built from the server background context
(MutatePlainMergeTreeTask::createTaskContext), and MergeTreeMutationEntry persists no settings,
so nothing carries the pin across. The old-analyzer lanes set the value in the default profile
(tests/config/users.d/analyzer.xml), which that background context inherits, so those two rows
would have failed there.

Both parties converged on this mechanism independently, and it was reproduced on a server carrying
that profile verbatim: the pre-fix file fails, and measured per row only the alias-subcolumn row was
the carrier (its a._table must be resolved through the alias expression while the part is read).

Both rows are now deleted. Neither mentioned _sample_factor; both pinned the behaviour of the
raw-AST guard this branch removes, which is plain master behaviour. One pin survives, on the
real-column-override row, whose NOT_FOUND_COLUMN_IN_BLOCK is raised during validation in the
client context that the pin does reach. That validation-versus-execution split is the whole
distinction. The file now passes unpinned on the old-analyzer profile, so both lanes keep full
coverage of the behaviour this PR changes, and removing the surviving pin reddens three of the six
measured routes.

⚠️ Closes: was only inside the template comment (fixed)

The draft description had the Closes: relationship inside the HTML comment block, where it does
not render and does not link the issue. Since the description is updated in place on this PR, that
draft would have removed the active linkage this PR already has, so the standalone line is restored.
Verified that issue #78465 is currently registered as a closing reference, and that this body shape
already passes Config Workflow, Finish Workflow and Style check.

💡 Test comments do not backtick literal SQL names (noted, not fixed)

The repository convention is to wrap literal SQL names in inline code, and the six comment lines in
the new test mention _sample_factor, Tuple, _table and _database without backticks, while
the source comment in the same change does use them. That inconsistency is real. It is comments
only, with no functional effect, so it is recorded rather than changed here; happy to backtick both
halves consistently if preferred.

✅ DISAGREE with measurements: the on-the-fly preview divergence is pre-existing and out of scope

The second pass raised, as a blocker, that with apply_mutations_on_fly = 1 a sampled read of an
unmaterialized mutation evaluates _sample_factor with the foreground query's factor rather than
the fixed 1 the background mutation will use. The observation is correct, but it is not this
change and not its contract:

  • Out of diff. All three files it cites (MergeTreeReadPoolBase.cpp, AlterConversions.cpp,
    ReadFromMergeTree.cpp) are byte-identical to the merge base at this head, compared per file.
    This change is three files: MergeTreeSequentialSource.cpp plus the two new test files.
  • The cited path never enters the changed function. Neither MergeTreeReadPoolBase.cpp nor
    MergeTreeReadPool.cpp nor MergeTreeReadTask.cpp references
    createMergeTreeSequentialSource at all.
  • Measured identical before and after. Running that exact fixture on a pristine master build
    and on this build, with each binary's build id verified, prints byte-identical results
    (onfly_sampled 2 2 2 100, without_onfly 0 0 2 100) on both arms. The divergence exists
    unchanged on master.
  • The contract is met. This change's stated invariant is that a mutation reads _sample_factor
    as 1. With mutations_sync = 2, so the background materialization actually completes, the
    pristine build fails with UNFINISHED while this build persists 1. Before this change there
    was no eventual value to agree with, which is also why the reported control row still reads 0.

That preview path is a distinct pre-existing concern, reachable only under a setting that is off by
default, and a fix there would need its own binding for pending-mutation actions so the outer
query's values are preserved. It is tracked separately alongside the _table/_database design
question, rather than folded into a three-line change.

Session id: cron:clickhouse-review-slot-11:20260731-033001

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100 percent on demand, no randomization needed. On a guard-free seed-free master build: CREATE TABLE s1 (c0 UInt32, u Float64) ENGINE=MergeTree ORDER BY c0 SAMPLE BY c0; INSERT INTO s1 VALUES (1,0),(5,0); ALTER TABLE s1 UPDATE u = _sample_factor WHERE c0 < 2 SETTINGS mutations_sync=2; gives Code: 341 wrapping Code: 16 Unexpected const virtual column: _sample_factor: While executing MergeTreeSequentialSource, system.mutations.is_done = 0, data unchanged. The non-matching row (AND c0 < 2) is required: with every row matching, the mutation degenerates to a whole-part drop and the part is never read.
b Root cause explained? _sample_factor is an Ephemeral virtual registered with VirtualsMaterializationPlace::Reader, so a reader must supply its value. ReadFromMergeTree::initializePipeline publishes it into shared_virtual_fields (ReadFromMergeTree.cpp:4122) and MergeTreeReadPoolBase.cpp:276 copies that map into every read task, so SELECT resolves it. createMergeTreeSequentialSource seeds only _part_index and _part_starting_offset (MergeTreeSequentialSource.cpp:331-332), so IMergeTreeReader::fillVirtualColumns finds nothing in virtual_fields, falls through to getFieldForConstVirtualColumn, and throws (MergeTreeVirtualColumns.cpp:89). One read path omits what its sibling copies wholesale.
c Fix matches root cause? Yes. It seeds the missing field at the omission site, three lines beside the two existing seeds, in a function that already receives const MergeTreeData & storage. The value is not invented: used_sample_factor is declared = 1.0 (ReadFromMergeTree.h:35) and is overwritten only inside if (sampling.use_sampling) with relative_sample_size != 0 (MergeTreeDataSelectExecutor.cpp:395, the sole writer); no SAMPLE clause can reach this path, so it is exactly the unsampled case. Mark pruning is not sampling: ReadFromPart::initializePipeline can prune marks from the primary key and WhatIfEmpiricalEstimator passes an explicit mark range, so the invariant is the absence of SAMPLE rather than a whole-part read. Measured on master: an unsampled SELECT returns 1, SAMPLE 0.5 returns 2, SAMPLE 0.25 returns 4. LazyReadFromMergeTreeSource.cpp:246 already publishes 1.0 the same way.
d Test intent preserved / new tests added? Yes. 04510 asserts the value, not just the absence of an exception, across the UPDATE right-hand side, the UPDATE predicate, ALTER DELETE, and lightweight DELETE FROM, plus a SELECT-path control that checks the seeded constant against what ReadFromMergeTree publishes independently, and must-not-regress rows for a real Tuple subcolumn, a lambda parameter, the unchanged _table/_database failure, and the pre-existing real-column-override failure. One file, 57 lines, 7 comment lines, each a single sentence naming what a section pins rather than a rationale block, and 2 serverError annotations. Two rows that pinned the behaviour of the now-deleted analysis-time guard were removed after measurement showed a per-statement SETTINGS enable_analyzer = 1 cannot reach the background mutation context; neither mentioned _sample_factor. Each surviving row is mutation-proven load-bearing, including the SELECT control, whose reversion to its earlier position makes the test fail.
e Both directions demonstrated? Yes, on two Build-ID-verified binaries, with the server's buildId() asserted against readelf -n on every start. The test FAILS on the pristine master snapshot (0da1aff10fd5, whose copy of the touched file is md5-identical to origin/master and is both seed-free and guard-free) with Code 341 wrapping Code 16 Unexpected const virtual column: _sample_factor, output stopping after the SELECT control row; it PASSES on the fix build (db68cd332cfb). The SELECT control passes on both arms, which is correct, since it exercises the already-working SELECT path. Two mutations, each rebuilt with a moved Build ID: reverting the seed reddens at the first _sample_factor row with that same signature; seeding 0.0 instead of 1.0 produces zero exceptions, so an abort-only oracle is provably blind and only the value assertions catch it (update rhs 1 to 0, update where 1,7 to 0,0, alter delete 1 to 2, lightweight delete 0 to 2). Restoring the fix relinked bit-identically to the shipping Build ID with the object file md5-identical, so no mutation residue ships.
f Fix is general across code paths? Yes, and it is fixed at the origin rather than guarded at the throw site. createMergeTreeSequentialSource is the single construction point for the per-part source. It has two direct call sites, ReadFromPart::initializePipeline (MergeTreeSequentialSource.cpp:471) and WhatIfEmpiricalEstimator.cpp:144, and the first is reached by every mutation and merge through createReadFromPartStep (MergeTreeSequentialSource.cpp:504), whose three callers are MutationsInterpreter.cpp:2249 and MergeTask.cpp:1788 and :3103. So all four consumers are covered by construction. Re-grepped shared_virtual_fields tree-wide: emplace for these names appears only at ReadFromMergeTree.cpp:4122-4124, so no fourth name has appeared. No merge-path consumer assumed the throw: _sample_factor appears nowhere in MergeTask.cpp, MutateTask.cpp or WhatIfEmpiricalEstimator.cpp, and the message Unexpected const virtual column has exactly one occurrence tree-wide, its own throw site, with zero tests referencing it.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The seeded value is a single Float64 constant, so there is no type-wrapper matrix on the fix itself; the matrix that matters is the shapes that resolve the NAME, and the test covers a direct reference, a real Tuple subcolumn, and a lambda parameter, in both the predicate and the assignment right-hand side, across the SELECT path, heavy ALTER UPDATE, heavy ALTER DELETE, and lightweight DELETE FROM. The analyzer axis was measured with the CI server profile rather than a client option, because a mutation executes in the background task context and a per-statement or session setting cannot reach it. On a server carrying tests/config/users.d/analyzer.xml verbatim (the fragment the two dedicated old-analyzer lanes install), the file passes with no file-level tag, so those lanes keep full coverage of the behaviour this PR changes. Exactly one statement needs a pin: the real-column-override must-not-regress row pins enable_analyzer = 1, validate_mutation_query = 1 because its pre-existing NOT_FOUND_COLUMN_IN_BLOCK is raised during analyzer-driven mutation validation, in the client context the pin does reach, and disappears when either setting is off. That divergence is pre-existing, reading identically on the pristine snapshot. The file passes on all six routes measured: default, the old-analyzer server profile, validate_mutation_query=0, and compatibility 23.1 / 24.3 / 25.1. Removing the single pin reddens three of them, validate_mutation_query=0, compatibility=23.1 and compatibility=24.3, and leaves default, compatibility=25.1 and the old-analyzer profile green, so the pin is load-bearing and is about mutation validation rather than about the analyzer.
h Backward compatible? Yes, and nothing is deliberately broken. No new setting, no SettingsChangesHistory.cpp entry, no serialization, format or protocol change, nothing persisted, no analyzer code touched. All three columns are Ephemeral (MergeTreeData.cpp:842 for _sample_factor) and every write-side consumer filters VirtualsKind::Persistent (MutationsInterpreter.cpp:525 and :1134; MergeTask.cpp:2889 and :3245; MutateTask.cpp:3392 and :3607), so the seed cannot put a new column into a part. The behaviour change is strictly permissive: a mutation that used to wedge now completes. _table/_database keep their existing pre-existing failure, verified byte-identical on both arms.
i Invariants and contracts preserved? Yes. The invariant is that every virtual column ReadFromMergeTree publishes into shared_virtual_fields, whose value is well defined and replica-invariant for a single part, must also be published by the per-part read path. _sample_factor is a literal constant, identical on every replica, and the seed sits in a function taking MergeTreeData, above the MergeTree/SharedMergeTree split, so both engines are covered by construction. _table and _database are deliberately excluded because they derive from the local storage id, which replicas are not required to share (only structure is checked against ZooKeeper), and a mutation persists what it reads. const_virtual_fields is a plain map populated before any reader is constructed, on one path with no early return between the existing seeds and the new one, and emplace cannot displace an existing entry. No range-reader virtual is added, so the IMergeTreeReader.cpp:147-148 guard is untouched.

Session id: cron:clickhouse-review-slot-11:20260731-033001

@groeneai

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

Two review rounds ran on this redesign: an independent cold review of the resulting code plus a
separate second-model pass, adjudicated against the recorded evidence. Round 1 found a blocker and
bounced; this round is clean. 3 findings adjudicated: 2 AGREE (both fixed), 1 DISAGREE with
measurements.

❌ Round 1 blocker, fixed: a per-statement analyzer pin cannot reach mutation execution

Two test rows carried SETTINGS enable_analyzer = 1 so they would behave the same on the two
dedicated old-analyzer lanes. That pin reaches the client and validation context only. A mutation
executes in a background task context built from the server background context
(MutatePlainMergeTreeTask::createTaskContext), and MergeTreeMutationEntry persists no settings,
so nothing carries the pin across. The old-analyzer lanes set the value in the default profile
(tests/config/users.d/analyzer.xml), which that background context inherits, so those two rows
would have failed there.

Both parties converged on this mechanism independently, and it was reproduced on a server carrying
that profile verbatim: the pre-fix file fails, and measured per row only the alias-subcolumn row was
the carrier (its a._table must be resolved through the alias expression while the part is read).

Both rows are now deleted. Neither mentioned _sample_factor; both pinned the behaviour of the
raw-AST guard this branch removes, which is plain master behaviour. One pin survives, on the
real-column-override row, whose NOT_FOUND_COLUMN_IN_BLOCK is raised during validation in the
client context that the pin does reach. That validation-versus-execution split is the whole
distinction. The file now passes unpinned on the old-analyzer profile, so both lanes keep full
coverage of the behaviour this PR changes, and removing the surviving pin reddens three of the six
measured routes.

⚠️ Closes: was only inside the template comment (fixed)

The draft description had the Closes: relationship inside the HTML comment block, where it does
not render and does not link the issue. Since the description is updated in place on this PR, that
draft would have removed the active linkage this PR already has, so the standalone line is restored.
Verified that issue #78465 is currently registered as a closing reference, and that this body shape
already passes Config Workflow, Finish Workflow and Style check.

💡 Test comments do not backtick literal SQL names (noted, not fixed)

The repository convention is to wrap literal SQL names in inline code, and the six comment lines in
the new test mention _sample_factor, Tuple, _table and _database without backticks, while
the source comment in the same change does use them. That inconsistency is real. It is comments
only, with no functional effect, so it is recorded rather than changed here; happy to backtick both
halves consistently if preferred.

✅ DISAGREE with measurements: the on-the-fly preview divergence is pre-existing and out of scope

The second pass raised, as a blocker, that with apply_mutations_on_fly = 1 a sampled read of an
unmaterialized mutation evaluates _sample_factor with the foreground query's factor rather than
the fixed 1 the background mutation will use. The observation is correct, but it is not this
change and not its contract:

  • Out of diff. All three files it cites (MergeTreeReadPoolBase.cpp, AlterConversions.cpp,
    ReadFromMergeTree.cpp) are byte-identical to the merge base at this head, compared per file.
    This change is three files: MergeTreeSequentialSource.cpp plus the two new test files.
  • The cited path never enters the changed function. Neither MergeTreeReadPoolBase.cpp nor
    MergeTreeReadPool.cpp nor MergeTreeReadTask.cpp references
    createMergeTreeSequentialSource at all.
  • Measured identical before and after. Running that exact fixture on a pristine master build
    and on this build, with each binary's build id verified, prints byte-identical results
    (onfly_sampled 2 2 2 100, without_onfly 0 0 2 100) on both arms. The divergence exists
    unchanged on master.
  • The contract is met. This change's stated invariant is that a mutation reads _sample_factor
    as 1. With mutations_sync = 2, so the background materialization actually completes, the
    pristine build fails with UNFINISHED while this build persists 1. Before this change there
    was no eventual value to agree with, which is also why the reported control row still reads 0.

That preview path is a distinct pre-existing concern, reachable only under a setting that is off by
default, and a fix there would need its own binding for pending-mutation actions so the outer
query's values are preserved. It is tracked separately alongside the _table/_database design
question, rather than folded into a three-line change.

Session id: cron:clickhouse-review-slot-11:20260731-033001

@groeneai

Copy link
Copy Markdown
Collaborator Author

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:

  • Reduce diff. The net change against master is now 3 files, +71/-0: three lines in MergeTreeSequentialSource.cpp plus one test. MutationsInterpreter.cpp and MergeTreeVirtualColumns.{h,cpp} are byte-identical to the merge base, so the previous 193-line guard is gone rather than moved.
  • Remove all comments. The test is down to 7 single-sentence lines naming what each section pins, and the source hunk carries 2. Happy to cut further if you want them all gone.
  • Simpler tests, do not mix cases. serverError annotations went from 18 to 2, and the test now asserts the materialized value rather than the absence of an exception.
  • Single test file. One file, 57 lines.

The reason Reader is the right place is your own e7487293, which deliberately moved _table/_database from Plan to Reader and added them to shared_virtual_fields. _sample_factor is registered the same way, ReadFromMergeTree publishes it and the read pool copies that map into every task, but createMergeTreeSequentialSource seeded only _part_index and _part_starting_offset, so a mutation threw. It now seeds 1, which is what an unsampled read already reports; used_sample_factor is declared 1.0 and is only overwritten for an actual SAMPLE clause.

Two things I deliberately left out of scope, both filed separately: _table/_database still fail mid-execution, because they derive from the local storage id and a mutation persists what it reads, so seeding them could diverge replicas while rejecting them everywhere would be a new restriction; and a real column named like a virtual one fails with NOT_FOUND_COLUMN_IN_BLOCK, which is pre-existing and pinned here as a must-not-regress row.

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.60% 78.60% +0.00%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1b8c928

CI is fully finished on this head with no failing checks: all 174 check-runs completed,
zero failures, and CIDB returns no FAIL/ERROR test rows for this commit.

Check / test Reason Owner / fixing PR
(none) - -
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260804-043000

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026

@alexey-milovidov alexey-milovidov left a comment

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.

This is perfect.

@alexey-milovidov alexey-milovidov self-assigned this Aug 21, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 21, 2026
Merged via the queue into ClickHouse:master with commit 16bea11 Aug 21, 2026
180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 25.8, 26.3, 26.5, 26.6, 26.7. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 builds.clickhouse.com, carrier = this PR's own test arm (ALTER TABLE ... UPDATE u = _sample_factor):

  • 25.8.33.3, 26.3, 26.5, 26.6, 26.7.6.4: all fail Code: 341 ... 'Unexpected const virtual column: _sample_factor' (NO_SUCH_COLUMN_IN_TABLE).
  • Control on master 26.8.1.1867, which has the fix: passes, no error. So the control discriminates.

The cherry-pick is clean and lands the whole fix. git merge-tree --write-tree --merge-base=<merge^1> <branch> <merge> returns rc=0 on all five, each resolved tree carrying exactly 3 source lines plus the 71-line test, and the one symbol the fix introduces present with no consumer left behind. (A plain git apply of the hunk fails at full context on all five, but only because master renamed data_part to data_part_info on adjacent lines; -C1 is clean everywhere and the anchor emplaces are verbatim on every branch. Context drift, not a conflict.)

Caveat 1: one label, not five. select_backport_branches expands a version-specific label to that release plus every newer active branch, so v25.8-must-backport alone yields ['25.8', '26.3', '26.5', '26.6', '26.7'], exactly the set requested. I do not open manual backport PRs; the label has to come from a maintainer. @alexey-milovidov, you merged this one, so could you apply v25.8-must-backport here and let the robot produce the five?

Caveat 2: the test file does not port below 26.6. Two of its serverError annotations describe behaviour of adjacent pre-existing bugs that differs on older branches, so the robot's mechanically-clean tree will still fail its own test on 25.8, 26.3 and 26.5:

arm annotated 25.8 26.3 26.5 26.6 26.7
DELETE WHERE _table != '' UNFINISHED no error, mutation succeeds UNKNOWN_IDENTIFIER ok ok ok
DELETE WHERE _sample_factor = 0.5 on a table with a real _sample_factor column NOT_FOUND_COLUMN_IN_BLOCK no error no error no error ok ok

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:

25.8 / 26.3 / 26.5 / 26.6 / 26.7:  pending plain 100, pending sampled 0     (divergence present)
same, apply_mutations_on_fly = 0:  pending plain 100, pending sampled 100   (control)
master 26.8.1.1867, with the fix:  pending plain 100, pending sampled 0     (unchanged)

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 UNFINISHED mutation half without shipping any new partial behaviour. The mechanism you describe is real and I am not closing #115837; it is tracked separately.

clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Aug 22, 2026
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
@groeneai

Copy link
Copy Markdown
Collaborator Author

Gentle ping on the one open item here: @alexey-milovidov, could you apply v25.8-must-backport to this PR? That single label expands to 25.8, 26.3, 26.5, 26.6 and 26.7, which is the whole requested set, and I verified the cherry-pick is clean on all five. Details and the two caveats are in #109813 (comment). Thanks.

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 groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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

Development

Successfully merging this pull request may close these issues.

_sample_factor missing column in mutation

6 participants