Skip to content

Parse mutation command AST on demand - #104886

Merged
nikitamikhaylov merged 12 commits into
masterfrom
mutation-command-lazy-ast
May 26, 2026
Merged

nikitamikhaylov merged 12 commits into
masterfrom
mutation-command-lazy-ast

Conversation

@nikitamikhaylov

@nikitamikhaylov nikitamikhaylov commented May 13, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Internal refactor of MutationCommand. No user-visible change except reduced memory usage in certain cases.

Description

MutationCommand used to hold a clone of the entire ASTAlterCommand (in the ast field) plus separate clones of its predicate, partition, and column_to_update_expression subtrees - the same data stored two-and-a-half times. This change replaces those fields with a single serialized ast_text (the output of formatWithSecretsOneLine) and lazy accessors that re-parse it via ParserAlterCommandList on demand:

  • MutationCommand::ast()
  • MutationCommand::predicate()
  • MutationCommand::partition()
  • MutationCommand::columnToUpdateExpression()

All call sites that previously read these fields now invoke the accessors. Sites that built a MutationCommand by hand (e.g. InterpreterDeleteQuery::execute) now construct an ASTAlterCommand, format it once, and store the text - the subtree fields no longer exist.

The serialization format on ZooKeeper / on-disk mutation entries is unchanged: ast_text is produced by formatWithSecretsOneLine, which round-trips through the same ParserAlterCommandList that MutationCommands::readText already uses. The gtest_mutation_commands round-trip test is unaffected.

Documentation entry for user-facing changes

  • Documentation change is not required

Version info

  • Merged into: 26.6.1.167

Replace the heavy `ASTPtr` fields stored in `MutationCommand` (`ast`,
`predicate`, `partition`, `column_to_update_expression`) with a single
serialized string `ast_text` and lazy accessors that re-parse it on
demand.

`MutationCommand` previously held a clone of the full `ASTAlterCommand`
plus separate clones of its `predicate`, `partition`, and update-
assignment subtrees - the same data tree stored two and a half times.
Now we keep only the formatted text and parse it back through
`ParserAlterCommandList` when an accessor is called. The serialization
format used for ZK and on-disk mutation entries is unchanged, since the
text is produced by `formatWithSecretsOneLine` and round-trips through
the same parser already used by `MutationCommands::readText`.

New methods on `MutationCommand`:
  - `ast() const`
  - `predicate() const`
  - `partition() const`
  - `columnToUpdateExpression() const`

Callers that previously read the fields now invoke these accessors;
sites that constructed mutation commands by hand (e.g.
`InterpreterDeleteQuery::execute`) now build an `ASTAlterCommand`,
format it, and store the text instead of assigning to fields.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1118b94]

Summary: ✅


AI Review

Summary

This PR replaces cached MutationCommand AST/subtrees with serialized ast_text and on-demand parsing, and updates call sites to read parsed fields via accessors. The refactor direction is reasonable, but the current head still reparses the same mutation commands repeatedly on hot per-part paths, which creates a high risk of mutation-preparation CPU regression.

Findings

❌ Blockers

  • [src/Storages/MutationCommands.cpp:91] MutationCommand::ast reparses ast_text on every call, with no memoization.
  • [src/Interpreters/MutationsInterpreter.cpp:236] and [src/Interpreters/MutationsInterpreter.cpp:139] parse each command per part in isStorageTouchedByMutations, then parse all commands again in prepareQueryAffectedAST for the same part.
  • [src/Storages/MergeTree/MutateTask.cpp:2618] parses command AST again in canSkipMutationCommandForPart inside the per-part command loop.
  • Impact: former field reads became repeated parser work in hot loops (command × part, plus extra full-pass reparse), which can significantly reduce mutation throughput and increase scheduler CPU for large part counts or wide mutations.
  • Suggested fix: keep a lazy cached parsed ASTAlterCommand inside MutationCommand (invalidate on ast_text update), or pre-parse each command once per preparation pass and thread parsed commands through all checks.
Tests
  • ⚠️ Add focused before/after evidence for mutation-preparation CPU cost (many parts, multiple UPDATE/DELETE commands), showing parser overhead is not regressed.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
  1. Remove repeated hot-path reparsing of mutation commands (cache or single-pass parsed reuse).
  2. Provide targeted performance evidence for mutation preparation after the refactor.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label May 13, 2026
if (ast_text.empty())
return nullptr;

ParserAlterCommandList p_alter_commands;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This accessor reparses ast_text on every call. In hot paths we now call predicate, partition, and columnToUpdateExpression repeatedly per command and per part (for example in MutationsInterpreter::prepare and StorageMergeTree::selectPartsToMutate), so one parsed mutation command becomes many parser runs and many AST clones.

That can significantly regress mutation throughput and scheduler CPU for wide UPDATE queries or large part counts. Please cache the parsed ASTAlterCommand inside MutationCommand (lazy) and reuse it across these accessors, or otherwise avoid reparsing in inner loops.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is still live in the current head.

Beyond the CPU regression, this also introduces a correctness regression: MutationCommand::ast reparses ast_text with hardcoded DBMS_DEFAULT_MAX_PARSER_DEPTH / DBMS_DEFAULT_MAX_PARSER_BACKTRACKS on every accessor call. A mutation command that was accepted under non-default parser limits can now fail later in execution (e.g. from MutationsInterpreter / AlterConversions) with a parser exception during these reparses.

Please keep a lazy cached parsed AST inside MutationCommand (or preserve the original parsed AST when available) and make predicate, partition, and columnToUpdateExpression reuse it instead of reparsing.

@antonio2368

Copy link
Copy Markdown
Member

No user-visible change

Reduced memory usage?

@antonio2368 antonio2368 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.

Let's make sure that we minimize amount of parsing where possible

Comment on lines +145 to +146
auto predicate = command.predicate();
if (command.type != MutationCommand::DELETE || command.partition() || !predicate)

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.

You are parsing it twice back to back here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Hmm, where? The one in the if statement is command.partition() which is not a command.predicate().

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.

But both partition and predicate call ast() right?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

MutationCommand::partition and MutationCommand::predicate both call MutationCommand::ast, so this condition reparses ast_text again after parsing predicate one line above.

So the concern is still valid: on the DELETE path we parse once for predicate, then once more for partition in the same call. It would be better to parse once (e.g. auto command_ast = command.ast();) and read both fields from that AST.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You're absolutely right!

Comment on lines +501 to +508
new_command.predicate()->collectIdentifierNames(source_columns);
filtered_commands.push_back(std::move(new_command));
}

if (!new_updated_columns.empty())
{
auto new_command = createCommandWithUpdatedColumns(command, std::move(new_updated_columns));
new_command.predicate->collectIdentifierNames(source_columns);
auto new_command = createCommandWithUpdatedColumns(command, new_updated_columns);
new_command.predicate()->collectIdentifierNames(source_columns);

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.

Not sure if they can be called in single function call, but again parsing twice.

@antonio2368 antonio2368 self-assigned this May 14, 2026
@Algunenano Algunenano added the comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... label May 14, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

alexey-milovidov and others added 3 commits May 17, 2026 21:08
`MutationCommand::ast` used to re-parse `ast_text` with hardcoded
`DBMS_DEFAULT_MAX_PARSER_DEPTH` / `DBMS_DEFAULT_MAX_PARSER_BACKTRACKS`,
so a command that was originally accepted under non-default parser
limits could fail later in execution (e.g. from `MutationsInterpreter`
or `AlterConversions`) with a parser `exception` during the on-demand
re-parse.

Store the limits used by the original successful parse on the
`MutationCommand` (`max_parser_depth` / `max_parser_backtracks`) and
use them in `ast` so subsequent re-parses stay consistent. The AST
is still parsed on demand - the limits are kept as constants on the
entry, not as a cached AST.

`MutationCommand::parse` now takes both limits as parameters (defaults
match the previous behavior). Call sites that have a `Context`
forward `Setting::max_parser_depth` / `Setting::max_parser_backtracks`;
derived constructions (`AlterConversions::createLightweightDeleteCommand`,
`createCommandWithUpdatedColumns`, `AlterCommands::getMutationCommands`'s
direct `ALTER_WITHOUT_MUTATION` push) carry the limits over from the
source command. Addresses review at
#104886 (comment)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`MutationCommand::predicate`, `partition` and `columnToUpdateExpression`
each re-parsed `ast_text` independently, so a hot path that reads more
than one of them parsed the same text several times. Replace those
three accessors (plus the previous `ast()`) with a single
`MutationCommand::accessAst` that returns a RAII handle:

  * parses `ast_text` once on construction (using the stored parser
    limits from the previous commit);
  * exposes the parsed `ASTAlterCommand` and clone-returning helpers
    `getPredicate` / `getPartition` / `getColumnToUpdateExpression`,
    so a single scope can read several sub-trees without re-parsing;
  * on destruction serializes the (possibly modified) AST back into
    the owning `MutationCommand::ast_text`, so any in-place edits
    persist;
  * is move-only; when constructed from a `const MutationCommand`
    it skips the write-back.

Hot paths that previously read more than one sub-tree are rewritten
to cache the handle once per scope:
`MutationsInterpreter::{isStorageTouchedByMutations, prepare,
getPartitionAndPredicateExpressionForMutationCommand}`,
`MutationsNonDeterministicHelpers::findFirstNonDeterministicFunction`,
`AlterConversions::{createCommandWithUpdatedColumns,
createLightweightDeleteCommand, filterMutationCommands,
addMutationCommand}`, `MergeTreeData::checkMutationCommandsImpl`,
`PatchPartsLock::getUpdateAffectedColumns` and
`StorageSystemWasmModules::getModuleDeleteFilterFromAst`. Addresses
the parsing-twice review comments at
#104886 (comment)
and
#104886 (comment).

The AST is still parsed on demand - it is never cached on the
`MutationCommand` between accesses, only for the lifetime of one
`AccessedAst` handle.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Storages/MutationCommands.cpp Resolved
Change `getPredicate` / `getPartition` to return `IAST *` and
`getColumnToUpdateExpression` to return a `const std::unordered_map<
String, ASTPtr> &` to a map cached lazily inside the handle. The
sub-trees now share storage with the AST owned by the handle - no
extra clones - so a single `accessAst` call is enough to read all
of them and to mutate them in place; the accumulated changes are
serialized back to `MutationCommand::ast_text` exactly once when
the handle is destroyed.

To make accidental dangling impossible, these accessors (and
`operator*` / `operator->`) are restricted to lvalue handles via
`& only` qualifiers, with `&& = delete` rvalue overloads. Callers
that previously chained `command.accessAst().getXxx()` now have to
bind the handle to a named variable first, which is exactly the
"create once, accumulate, write back once" pattern.

Callers updated accordingly. Where a raw `IAST *` from the handle
needs to be passed to APIs that expect an `ASTPtr`, the caller
explicitly wraps it via `ASTPtr(raw)` to add an intrusive reference
(e.g. `buildQueryTree`, `getPartitionIDFromQuery`, `makeASTOperator`,
the `FirstNonDeterministicFunctionFinder` visitor). The mutation in
`AlterConversions::createCommandWithUpdatedColumns` runs inside an
explicit scope so the handle's write-back to `res.ast_text` happens
before `return res`, regardless of NRVO.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Storages/MergeTree/MutateTask.cpp Outdated
static bool canSkipMutationCommandForPart(const MergeTreeDataPartPtr & part, const StorageMetadataPtr & metadata_snapshot, const MutationCommand & command, const ContextPtr & context)
{
if (command.partition)
auto handle = command.accessAst();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

canSkipMutationCommandForPart runs inside the per-part loop (for (const auto & command : *ctx->commands) in prepare). Calling command.accessAst() here reparses ast_text for every command/part combination just to check partition.

Before this refactor partition was a direct field read, so this turns a cheap check into parser work in a hot path and can noticeably increase mutation scheduler CPU for large part counts. Please avoid reparsing here (for example by caching parsed ASTAlterCommand in MutationCommand, or by storing partition in a parsed-once side structure reused across parts).

Comment thread src/Storages/MutationCommands.cpp Resolved
Address the open review on PR #104886
(#104886). The previous
`MutationCommand::accessAst` API mixed read and write into one RAII
handle, exposed three separate sub-tree accessors with lvalue-only
qualifiers, and had a move-assignment that called `this->~AccessedAst()`
followed by writes to the just-destroyed object - undefined behavior.

This commit splits the API in two:

  * `MutationCommand::ast() const` returns a shareable
    `boost::intrusive_ptr<const ASTAlterCommand>`. The AST is parsed on
    demand using the command's stored parser limits; the returned
    pointer owns the AST independently of the source `MutationCommand`,
    so callers may keep it, hand it on, or scope it as a local. The
    natural way to read several sub-trees in one place is now to bind
    `ast()` once and access `predicate`, `partition` and
    `update_assignments` directly on the returned pointer.

  * `MutationCommand::mutateAst()` returns a `MutableAst` RAII handle.
    Construction parses a fresh mutable copy of `ast_text`; on
    destruction the (possibly modified) AST is serialized back into
    `MutationCommand::ast_text` in one pass. The handle is non-copyable
    and non-movable, so there is no operator= to misuse.

A free helper `getColumnToUpdateExpression(const ASTAlterCommand &)`
replaces the previous handle-level method for sites that want the
`column -> expression` map.

Correctness fixes folded into this rework:

  * `InterpreterDeleteQuery::execute` now propagates
    `Setting::max_parser_depth` / `Setting::max_parser_backtracks` into
    `mut_command`, so a `DELETE` accepted under non-default session
    parser limits cannot later fail with a parser exception on
    re-parse. Same pattern already used in `InterpreterUpdateQuery` and
    `AlterCommands`. Addresses
    #104886 (comment).

  * Removed the move-assignment UB on the handle by making the new
    `MutableAst` non-movable. Addresses
    #104886 (comment).

All ~14 call sites that used `accessAst` are migrated to the new API.
Each compiles cleanly when invoked through the project's existing
`compile_commands.json`.

A note on the per-part parsing cost flagged in the review
(#104886 (comment),
#104886 (comment)):
the new API does not cache the parsed AST on `MutationCommand` itself
- doing so would require either a mutex (which makes the struct
non-copyable) or a custom copy-ctor that resets the cache (fragile,
must be kept in sync with every new field). The simpler `ast()` value
contract instead lets each scope decide: hot loops that read several
sub-trees per command (`MutationsInterpreter::prepare`,
`AlterConversions::filterMutationCommands`, etc.) now do exactly one
parse per command per scope, and the returned `intrusive_ptr` can be
held across the loop body. For per-part-per-command scheduling paths
(`MutateTask::canSkipMutationCommandForPart`,
`StorageMergeTree::selectPartsToMutate`) the cost is one parse of a
one-line `ALTER` body per call - microseconds - and is dominated by
the rest of the mutation-scheduling work. We can revisit with a real
cache if profiling shows otherwise.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@antonio2368 antonio2368 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.

Most other comments are written by the bot

Comment thread src/Storages/MutationCommands.h Outdated
Comment on lines +61 to +82
/// Read-only accessor: parses `ast_text` and returns the parsed alter
/// command as a shareable, const-qualified pointer. Returns nullptr if
/// `ast_text` is empty.
///
/// The returned value owns the AST: callers may keep it (passing through
/// further calls, storing in local variables, etc.) and it stays valid
/// independently of the `MutationCommand` it came from. To read several
/// sub-trees (`predicate`, `partition`, the `UPDATE` assignments) of the
/// same command, hoist `ast()` once into a local and access fields
/// directly through the returned pointer.
boost::intrusive_ptr<const ASTAlterCommand> ast() const;

/// RAII handle for editing the AST of a `MutationCommand` in place.
///
/// On construction the handle parses a fresh, mutable copy of `ast_text`.
/// Inside the handle's scope callers may freely mutate the AST through
/// `*handle` / `handle->...`. On destruction the (possibly modified) AST
/// is serialized back into the owning `MutationCommand::ast_text` in one
/// pass, so all edits accumulated through one handle are written back
/// exactly once.
///
/// The handle is neither copyable nor movable. Construct one per scope.

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.

I would shorten the comments

nikitamikhaylov and others added 4 commits May 22, 2026 17:15
* Cache the parsed `ASTAlterCommand` on `MutationCommand` so `ast()` no
  longer reparses `ast_text` on every call. All construction paths
  populate the cache up front through a new `setAst` helper or via
  `MutationCommand::parse` (which now refcounts the input AST directly
  instead of cloning).
* Replace the silent destructor-based write-back of `MutableAst` with
  an explicit, throwing `commit`. The destructor is cleanup-only and
  asserts in debug if `commit` was forgotten. Update the only caller
  (`createCommandWithUpdatedColumns`) accordingly.
* Hoist `getPartitionAndPredicateExpressionForMutationCommand` out of
  the per-assignment loop in `MutationsInterpreter::prepare` and clone
  the base predicate per assignment.
* Shorten the API docstrings on `MutationCommand::ast` and `MutableAst`.

PR: #104886

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous commit cached the parsed `ASTAlterCommand` on
`MutationCommand` to avoid reparsing. That defeated the original
motivation of the PR: stop holding the heavy-weight AST once it's
no longer needed.

Drop `cached_ast` and the `setAst` helper. `ast()` parses on each
call again; callers in hot loops already hoist the result into a
local (e.g. `auto alter = command.ast();`). The `MutableAst::commit`
fix and the `MutationsInterpreter` UPDATE-loop hoist from the
previous commit are unaffected and stay.

PR: #104886

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…utationCommand

Change the signature to accept the already-parsed `ASTAlterCommand *`
instead of a `MutationCommand`. Callers now hoist `auto alter =
command.ast();` once and pass `alter.get()` in, so the UPDATE branch
of `MutationsInterpreter::prepare` (and the DELETE / return-mutated
paths) parse the command exactly once per iteration instead of twice.

PR: #104886

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
else
{
if (!command.predicate) /// The command touches all rows.
auto alter = command.ast();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This loop runs for every candidate part in mutation preparation, so command.ast() here reparses ast_text for each command × part pair.

After this PR, we already do another per-part parse in canSkipMutationCommandForPart, so large mutations now pay parser cost twice on the hot path before execution. Could we parse each command once per part-preparation pass (or cache per-command parsed ASTAlterCommand) and reuse it in both checks?

for (const MutationCommand & command : commands)
{
if (ASTPtr condition = getPartitionAndPredicateExpressionForMutationCommand(command, storage, context))
auto alter = command.ast();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

isStorageTouchedByMutations already iterates commands per part and calls command.ast(). This helper then reparses every command again when building the count() predicate (command.ast() in this loop), so affected parts pay an extra full parse pass before execution.

Given this runs on the mutation preparation hot path, this compounds the regression from on-demand parsing. Please thread a parsed-command representation through this path (or cache the parsed ASTAlterCommand per MutationCommand) so this second per-part parse pass is avoided.

…zy-ast

# Conflicts:
#	src/Interpreters/InterpreterDeleteQuery.cpp
#	src/Interpreters/MutationsInterpreter.h
@clickhouse-gh

clickhouse-gh Bot commented May 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: 90.79% (434/478) | lost baseline coverage: 20 line(s) · Uncovered code

Full report · Diff report

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue May 26, 2026
Merged via the queue into master with commit 3e8c0c6 May 26, 2026
166 checks passed
@nikitamikhaylov
nikitamikhaylov deleted the mutation-command-lazy-ast branch May 26, 2026 18:31
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @nikitamikhaylov @antonio2368 — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The PR description is essentially empty (just the template). While the changelog entry explains the change, the PR body should describe the motivation, approach, and any testing done.

  • Suggested addition:

    This PR changes MutationCommand to store the AST as serialized text (ast_text) instead of keeping the parsed AST in memory. The AST is now parsed on-demand via the ast() method. This reduces memory usage for mutation commands that are stored but not immediately executed (e.g., queued mutations in ReplicatedMergeTree). The MutableAst RAII class provides safe in-place modification with explicit commit() semantics.

Ignore this if the current title/body is intentional.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... pr-not-for-changelog This PR should not be mentioned in the changelog 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.

6 participants