Repository navigation
Enable new analyzer for MutationsInterpreter (coded version 3) - #98884
Conversation
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]>
|
Workflow [PR], commit [56b4bd8] Summary: ❌
AI ReviewSummaryThis PR enables the analyzer/planner-based mutation path in Final Verdict
|
- 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]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
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(); | ||
| } |
There was a problem hiding this comment.
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)
yakov-olkhovskiy
left a comment
There was a problem hiding this comment.
overall LGTM, except that concern with validate() - please check
MutationsInterpreter (vibecoded version 3)MutationsInterpreter (groovecoded version 3)
MutationsInterpreter (groovecoded version 3)MutationsInterpreter (dope-coded version 3)
MutationsInterpreter (dope-coded version 3)MutationsInterpreter (coded version 3)
# 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.
…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.
LLVM Coverage Report
Changed lines: 98.43% (375/381) | lost baseline coverage: 5 line(s) · Uncovered code |
|
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. |
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
Enable new analyzer for `MutationsInterpreter` (coded version 3)
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


Remove the force-disable of
allow_experimental_analyzerinMutationsInterpreterand add a full new-analyzer code path inprepareMutationStagesusingQueryAnalyzer,PlannerContext,ActionsChain, andbuildActionsDAGFromExpressionNode.Key changes:
Use
TableNodewith real storage but emptyTableLockHolderto avoid deadlock (mutation thread already holds write lock).After
QueryAnalyzer::resolve, callcreateUniqueAliasesIfNecessaryto assign unique aliases to all table expressions, preventing column identifier collisions in nested subqueries.Add
use_storage_snapshot_without_dataflag toQueryAnalyzerso thatIdentifierResolver::tryResolveTableIdentifiercallsgetStorageSnapshotWithoutDatainstead ofgetStorageSnapshot. This avoids deadlock oncurrently_processing_in_background_mutexwhen an IN subquery references the table being mutated.Add
ignore_in_subqueriesflag toQueryAnalyzerto skip resolving the second argument of IN functions whenvalidate_mutation_query = 0, since the subquery may reference non-existent tables.Add referenced virtual columns and subcolumns to
input_columnsby queryingPlannerContexttable expression data aftercollectSourceColumns.Handle
MATERIALIZE COLUMNwith constant defaults by usinggetTableExpressionDataOrNullinstead 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_analyzercovering DELETE, UPDATE, DELETE with IN subquery, MATERIALIZE COLUMN, and Memory engine.Changelog category (leave one):
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
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 whenallow_experimental_analyzeris enabled, instead of force-disabling it inMutationsInterpreter. The new path resolves mutation expressions viaQueryAnalyzer/PlannerContextand builds anActionsChain, 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 aDelayedCreatingSetsStep, and mutation validation inInterpreterAlterQuery/InterpreterDeleteQueryis gated behind thevalidate_mutation_querysetting.Misc/test updates: fixes a virtual column loop control bug (
VirtualColumnUtils), factors outevaluateMutationCommandsSize()to avoid constructing a full interpreter during size checks, and updates/adds stateless tests (including a new03988_mutations_with_analyzersuite and ano-old-analyzertag) 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
26.6.1.105