Skip to content

Enable new analyzer for MutationsInterpreter (coded version 3) - #98884

Merged
KochetovNicolai merged 17 commits into
masterfrom
mutations-analyzer
May 22, 2026
Merged

KochetovNicolai merged 17 commits into
masterfrom
mutations-analyzer

Conversation

@KochetovNicolai

@KochetovNicolai KochetovNicolai commented Mar 5, 2026 •

Copy link
Copy Markdown
Member

Remove the force-disable of allow_experimental_analyzer in MutationsInterpreter and add a full new-analyzer code path in prepareMutationStages using QueryAnalyzer, PlannerContext, ActionsChain, and buildActionsDAGFromExpressionNode.

Key changes:

  • Use TableNode with real storage but empty TableLockHolder to avoid deadlock (mutation thread already holds write lock).

  • After QueryAnalyzer::resolve, call createUniqueAliasesIfNecessary to assign unique aliases to all table expressions, preventing column identifier collisions in nested subqueries.

  • Add use_storage_snapshot_without_data flag to QueryAnalyzer so that IdentifierResolver::tryResolveTableIdentifier calls getStorageSnapshotWithoutData instead of getStorageSnapshot. This avoids deadlock on currently_processing_in_background_mutex when an IN subquery references the table being mutated.

  • Add ignore_in_subqueries flag to QueryAnalyzer to skip resolving the second argument of IN functions when validate_mutation_query = 0, since the subquery may reference non-existent tables.

  • Add referenced virtual columns and subcolumns to input_columns by querying PlannerContext table expression data after collectSourceColumns.

  • Handle MATERIALIZE COLUMN with constant defaults by using getTableExpressionDataOrNull instead of the throwing variant.

  • Update test 00652_mergetree_mutations — alias columns are now supported in mutations with the new analyzer.

  • Add test 03988_mutations_with_analyzer covering DELETE, UPDATE, DELETE with IN subquery, MATERIALIZE COLUMN, and Memory engine.

Changelog category (leave one):

  • Improvement

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

Mutations uses a new analyzer.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

High Risk
High risk because it changes how ALTER UPDATE/DELETE/MATERIALIZE mutations are analyzed, planned, and how required/input columns and IN-subquery sets are built, which can affect correctness, performance, and deadlock behavior in a core data-mutation path.

Overview
Mutations (ALTER UPDATE/DELETE/materializations) can now run through the new analyzer/planner path when allow_experimental_analyzer is enabled, instead of force-disabling it in MutationsInterpreter. The new path resolves mutation expressions via QueryAnalyzer/PlannerContext and builds an ActionsChain, explicitly handling virtual columns/subcolumns, deterministic output ordering, and projection/input passthrough semantics needed for on-the-fly mutation application.

IN-subquery prepared sets are now planned explicitly on the new path by building subquery QueryPlans and adding a DelayedCreatingSetsStep, and mutation validation in InterpreterAlterQuery/InterpreterDeleteQuery is gated behind the validate_mutation_query setting.

Misc/test updates: fixes a virtual column loop control bug (VirtualColumnUtils), factors out evaluateMutationCommandsSize() to avoid constructing a full interpreter during size checks, and updates/adds stateless tests (including a new 03988_mutations_with_analyzer suite and a no-old-analyzer tag) to reflect analyzer-enabled mutation behavior and alias support.

Written by Cursor Bugbot for commit 4ee2d02. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.6.1.105

Remove the force-disable of `allow_experimental_analyzer` in
`MutationsInterpreter` and add a full new-analyzer code path in
`prepareMutationStages` using `QueryAnalyzer`, `PlannerContext`,
`ActionsChain`, and `buildActionsDAGFromExpressionNode`.

Key changes:

- Use `TableNode` with real storage but empty `TableLockHolder` to avoid
  deadlock (mutation thread already holds write lock).

- After `QueryAnalyzer::resolve`, call `createUniqueAliasesIfNecessary`
  to assign unique aliases to all table expressions, preventing column
  identifier collisions in nested subqueries.

- Add `use_storage_snapshot_without_data` flag to `QueryAnalyzer` so
  that `IdentifierResolver::tryResolveTableIdentifier` calls
  `getStorageSnapshotWithoutData` instead of `getStorageSnapshot`. This
  avoids deadlock on `currently_processing_in_background_mutex` when an
  IN subquery references the table being mutated.

- Add `ignore_in_subqueries` flag to `QueryAnalyzer` to skip resolving
  the second argument of IN functions when `validate_mutation_query = 0`,
  since the subquery may reference non-existent tables.

- Add referenced virtual columns and subcolumns to `input_columns` by
  querying `PlannerContext` table expression data after
  `collectSourceColumns`.

- Handle `MATERIALIZE COLUMN` with constant defaults by using
  `getTableExpressionDataOrNull` instead of the throwing variant.

- Update test `00652_mergetree_mutations` — alias columns are now
  supported in mutations with the new analyzer.

- Add test `03988_mutations_with_analyzer` covering DELETE, UPDATE,
  DELETE with IN subquery, MATERIALIZE COLUMN, and Memory engine.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [56b4bd8]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Integration tests (arm_binary, distributed plan, 3/4) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Integration tests (amd_tsan, 2/6) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Integration tests (amd_msan, 2/6) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Integration tests (amd_llvm_coverage, 3/5) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR enables the analyzer/planner-based mutation path in MutationsInterpreter, adds a server-wide use_analyzer_for_mutations override, wires mutation validation behavior for validate_mutation_query, and extends test coverage (including analyzer-only mutation cases and override behavior). I re-checked prior discussion points against current HEAD; the previously reported replicated non-determinism validation gap and missing forceMaterializeCTE in set-subquery planning are both fixed in code. No new correctness, safety, or compatibility issues were found in the current diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 5, 2026
KochetovNicolai and others added 9 commits March 6, 2026 19:17
- Use `PlannerActionsVisitor` instead of `buildActionsDAGFromExpressionNode`
  for filter and update steps, preserving output columns correctly for
  on-fly mutation application.

- Fix `project_input` on non-projection steps: `ActionsChain::finalize`
  sets `project_input = true` unconditionally, but columns like
  `_part_offset` must pass through. Match the old path by clearing it
  on all steps except the last (projection) one.

- Fix reading unnecessary columns: the identity DAG for stage 0 was
  initialized with all `input_columns`, preventing `finalize` from
  pruning. Use only `output_columns` to match the old path which uses
  `required_source_columns`.

- Use `dry_run` flag for `use_storage_snapshot_without_data` instead of
  always true, so self-referencing IN subqueries work during execution.

- Handle EXISTS in `ignore_in_subqueries` mode (resolveFunction.cpp):
  resolve as constant 0 when `validate_mutation_query = 0`.

- Fix tests: `03246_alter_update_dynamic_hung` now expects
  `UNKNOWN_TABLE` (new analyzer validates eagerly),
  `03571_trying_to_get_name_of_not_a_column_asterisk` accepts
  `UNSUPPORTED_METHOD`, `03173_forbid_qualify` works with mutations_sync,
  `03100_lwu_43_subquery_from_rmt` adds self-referencing IN subquery test.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Fix empty columns list when all expressions are constants:
When all mutation expressions are constants or scalar subqueries
(e.g. `UPDATE c0 = (), c1 = 2 WHERE EXISTS(SELECT 1)`), no table
columns are referenced and `getInputColumnNames` returns empty.
Add fallback to pick the smallest physical column, matching the
old `TreeRewriter::collectUsedColumns` behavior.

Fix duplicate columns causing constant value mismatch:
The update step output builder added updated columns twice — once
from the `output_columns` loop and once from `column_to_updated`.
Skip entries already in `output_columns` to avoid duplicates.

Also, `project_input` was incorrectly cleared on the first step of
every stage's actions chain. For stages beyond the first, the update
step needs `project_input` to properly replace columns and not pass
through old values alongside new ones. Only clear `project_input`
on the first step of stage 0.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The projection, filter, and update steps in `prepareMutationStages`
iterated over `stage.output_columns` (a `NameSet`, i.e.
`std::unordered_set`) to build DAG outputs. This produced
non-deterministic column ordering in the pipeline header.

Consumers like `EmbeddedRocksDBSink` expect columns in the table's
metadata order. When the hash-table iteration order didn't match,
serialization would attempt to cast a column to the wrong type,
causing a "Bad cast from type ColumnString to ColumnVector<unsigned int>"
exception in debug builds.

Fix: iterate `all_columns` (which preserves metadata order) instead of
the unordered `output_columns` set when building DAG outputs.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…shot_without_data`

Extract `evaluateMutationCommandsSize` as a free function that only
builds an AST and returns its size, without constructing a full
`MutationsInterpreter`. This eliminates the deadlock where
`selectPartsToMutate` holds `currently_processing_in_background_mutex`,
constructs `MutationsInterpreter`, which triggers `QueryAnalyzer::resolve`
on IN subqueries, calling `getStorageSnapshot` → `getMutationsSnapshot`
→ tries to lock the same mutex.

With this deadlock path gone, the `use_storage_snapshot_without_data`
flag in `QueryAnalyzer` and `IdentifierResolver` is no longer needed.
Remove it to reduce the blast radius on core analyzer infrastructure.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The `_row_number` handler in the virtual column loop used `return`
instead of `continue`, causing the function to exit early and skip
remaining virtual columns. This led to "Invalid number of columns
in chunk pushed to OutputPort" exceptions when reading from
object storage sources that request multiple virtual columns
(e.g. Iceberg DELETE mutations expecting `_path`, `_row_number`,
`_file`, `_size`, `_time`, `_etag`, `_tags`, etc.).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Implement the `no-old-analyzer` tag in `clickhouse-test` that skips
tests when `is_old_analyzer_used()` returns true. Tag the tests whose
expected output changes with the new analyzer mutations path.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…t caller

Instead of teaching `QueryAnalyzer` to skip resolving IN subqueries
when `validate_mutation_query = 0`, skip calling
`MutationsInterpreter::validate` entirely in `InterpreterAlterQuery`
and `InterpreterDeleteQuery`. This is cleaner: the analyzer stays
unchanged, and invalid mutations simply fail at execution time.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Combine multiple filter expressions using `FunctionNode("and")` +
`resolveOrdinaryFunctionNodeByName` directly on the already-resolved
query tree nodes, instead of going back to AST via `makeASTForLogicalAnd`,
rebuilding the query tree, and re-running `QueryAnalyzer`.

Also change the log message to only report when the old analyzer is used.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@KochetovNicolai
KochetovNicolai marked this pull request as ready for review March 13, 2026 14:39

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

{
MutationsInterpreter::Settings mutation_settings(false);
MutationsInterpreter(table, metadata_snapshot, mutation_commands, getContext(), mutation_settings).validate();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Non-deterministic check skipped when validate_mutation_query is false

Medium Severity

Wrapping the entire validate() call inside the validate_mutation_query check causes the non-deterministic function safety check for replicated tables to be bypassed when validate_mutation_query = false. Previously, validate() was always called and only the query structure validation (prepareQueryAffectedAST/InterpreterSelectQuery) was conditional on validate_mutation_query. Now the replicated-table non-deterministic guard and the plan validation inside validate() are also skipped, which could allow non-deterministic mutations on replicated tables leading to replica divergence.

Additional Locations (1)
Fix in Cursor Fix in Web

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.

@KochetovNicolai this concern seems reasonable

@yakov-olkhovskiy yakov-olkhovskiy 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.

overall LGTM, except that concern with validate() - please check

@alexey-milovidov alexey-milovidov changed the title Enable new analyzer for MutationsInterpreter (vibecoded version 3) Enable new analyzer for MutationsInterpreter (groovecoded version 3) Apr 10, 2026
@alexey-milovidov alexey-milovidov changed the title Enable new analyzer for MutationsInterpreter (groovecoded version 3) Enable new analyzer for MutationsInterpreter (dope-coded version 3) Apr 10, 2026
@alexey-milovidov alexey-milovidov changed the title Enable new analyzer for MutationsInterpreter (dope-coded version 3) Enable new analyzer for MutationsInterpreter (coded version 3) Apr 10, 2026
# Conflicts:
#	src/Interpreters/InterpreterAlterQuery.cpp
#	src/Interpreters/MutationsInterpreter.cpp
#	tests/clickhouse-test
After merging master, two breaking changes affect the new analyzer
mutation path in `MutationsInterpreter`:

- `StorageSnapshot::virtual_columns` was removed; virtuals now live in
  `metadata->virtuals` with explicit `VirtualsKind`/`VirtualsMaterializationPlace`.

- `GlobalPlannerContext` constructor gained a `parallel_replicas_table_union`
  parameter (master commit added support for parallel replicas under UNION).
Move the `validate_mutation_query` gate back inside `MutationsInterpreter::validate`
so it only skips the syntactic query-validation block, while the
`allow_nondeterministic_mutations` enforcement for `Replicated*` storages always
runs. Previously, gating the entire `validate` call at the caller in
`InterpreterAlterQuery::runCommandSegments` and `InterpreterDeleteQuery::execute`
silently bypassed the non-determinism safety check too.

Reported by review on #98884.
alexey-milovidov and others added 4 commits May 7, 2026 19:05
…uery=0

The previous fix for the regression that the master commit introduced (always
calling MutationsInterpreter::validate) only gated the syntactic
prepareQueryAffectedAST/QueryTree block inside validate. The QueryPlan build
that follows it (initQueryPlan -> prepareMutationStages) still ran
unconditionally, and on the new analyzer it now resolves IN subqueries through
QueryAnalyzer. With validate_mutation_query=0 and a subquery referencing a
non-existent table this throws UNKNOWN_TABLE during the DELETE/ALTER call —
exactly the path 03256_invalid_mutation_query exercises.

Also, even before validate is reached, constructing MutationsInterpreter calls
prepare which runs prepareMutationStages, so any inner gate inside validate is
unreachable.

Move the gate back to the callers (InterpreterDeleteQuery,
InterpreterAlterQuery::runCommandSegments) and extract the replicated-storage
non-determinism check into a static MutationsInterpreter helper that the
callers run unconditionally. The heavy MutationsInterpreter construction +
validate is now skipped when validate_mutation_query=0, while the
allow_nondeterministic_mutations enforcement still runs in every case — keeping
the safety the master commit was meant to restore.

Reported by Fast test run on #98884.
`buildSubqueryPlansForSetsAndAdd` mirrors `addBuildSubqueriesForSetsStepIfNeeded`
from the planner but missed the `forceMaterializeCTE` step on `subquery_options`.
Without it, an `IN` subquery that references a Materialized CTE would build its
plan without the CTE materialization step, diverging from the regular planner path.
Set the flag the same way the planner does.

Reported by review on #98884.
…or mutations

When set in the server config, this option overrides the session setting
`allow_experimental_analyzer` for `MutationsInterpreter`. Absent (default)
means the session setting is used.

The override is parsed once per config reload in `Server.cpp` and stored as
a tri-state atomic on the shared context, so each mutation only pays an
atomic load instead of re-reading the config.
@clickhouse-gh

clickhouse-gh Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 98.43% (375/381) | lost baseline coverage: 5 line(s) · Uncovered code

Full report · Diff report

@KochetovNicolai
KochetovNicolai added this pull request to the merge queue May 22, 2026
@KochetovNicolai

Copy link
Copy Markdown
Member Author

Test test_mysql_protocol/test.py::test_mysql_dotnet_client is fixed in #105636

I won't remerge with master, because sync will conflict again.

Merged via the queue into master with commit 72b4ed7 May 22, 2026
160 of 167 checks passed
@KochetovNicolai
KochetovNicolai deleted the mutations-analyzer branch May 22, 2026 21:26
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 22, 2026
alexey-milovidov added a commit that referenced this pull request May 24, 2026
Added to `known_complex_sections` so that `checkUnknownSettings` does not
reject the stock server config option introduced in #98884.

Integration test `test_mutations_analyzer_override` regressed in CI because
its config sets the `<use_analyzer_for_mutations>` top-level option, which
this PR's allowlist did not yet know about. Verified locally:
`Integration tests (amd_tsan, 1/6)`: `test_mutations_analyzer_override`
2 passed.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100332&sha=3953a413bea0c728f0f0001173001b9c4c40cd52&name_0=PR
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Enable new analyzer for `MutationsInterpreter` (coded version 3)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Added to `known_complex_sections` so that `checkUnknownSettings` does not
reject the stock server config option introduced in ClickHouse#98884.

Integration test `test_mutations_analyzer_override` regressed in CI because
its config sets the `<use_analyzer_for_mutations>` top-level option, which
this PR's allowlist did not yet know about. Verified locally:
`Integration tests (amd_tsan, 1/6)`: `test_mutations_analyzer_override`
2 passed.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100332&sha=3953a413bea0c728f0f0001173001b9c4c40cd52&name_0=PR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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.

4 participants