Repository navigation
Parse mutation command AST on demand - #104886
Conversation
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]>
|
Workflow [PR], commit [1118b94] Summary: ✅ AI ReviewSummaryThis PR replaces cached Findings❌ Blockers
Tests
Final Verdict
|
| if (ast_text.empty()) | ||
| return nullptr; | ||
|
|
||
| ParserAlterCommandList p_alter_commands; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Reduced memory usage? |
antonio2368
left a comment
There was a problem hiding this comment.
Let's make sure that we minimize amount of parsing where possible
| auto predicate = command.predicate(); | ||
| if (command.type != MutationCommand::DELETE || command.partition() || !predicate) |
There was a problem hiding this comment.
You are parsing it twice back to back here.
There was a problem hiding this comment.
Hmm, where? The one in the if statement is command.partition() which is not a command.predicate().
There was a problem hiding this comment.
But both partition and predicate call ast() right?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
You're absolutely right!
| 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); |
There was a problem hiding this comment.
Not sure if they can be called in single function call, but again parsing twice.
|
This was fixed by #105146. Let's update the branch. |
`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]>
…ckHouse into mutation-command-lazy-ast
`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]>
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]>
| static bool canSkipMutationCommandForPart(const MergeTreeDataPartPtr & part, const StorageMetadataPtr & metadata_snapshot, const MutationCommand & command, const ContextPtr & context) | ||
| { | ||
| if (command.partition) | ||
| auto handle = command.accessAst(); |
There was a problem hiding this comment.
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).
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
left a comment
There was a problem hiding this comment.
Most other comments are written by the bot
| /// 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. |
There was a problem hiding this comment.
I would shorten the comments
…on-command-lazy-ast
* 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(); |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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
LLVM Coverage Report
Changed lines: 90.79% (434/478) | lost baseline coverage: 20 line(s) · Uncovered code |
|
Hi @nikitamikhaylov @antonio2368 — a couple of suggestions to make this PR easier for reviewers and the changelog reader. Description (currently
Ignore this if the current title/body is intentional. |
Changelog category (leave one):
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
MutationCommandused to hold a clone of the entireASTAlterCommand(in theastfield) plus separate clones of itspredicate,partition, andcolumn_to_update_expressionsubtrees - the same data stored two-and-a-half times. This change replaces those fields with a single serializedast_text(the output offormatWithSecretsOneLine) and lazy accessors that re-parse it viaParserAlterCommandListon 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
MutationCommandby hand (e.g.InterpreterDeleteQuery::execute) now construct anASTAlterCommand, 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_textis produced byformatWithSecretsOneLine, which round-trips through the sameParserAlterCommandListthatMutationCommands::readTextalready uses. Thegtest_mutation_commandsround-trip test is unaffected.Documentation entry for user-facing changes
Version info
26.6.1.167