Skip to content

Treat a bare table identifier on the right of IN as a deferred set for mutation pruning - #117272

Merged
alexey-milovidov merged 28 commits into
masterfrom
fix-mutation-pruning-table-in-set
Nov 20, 2026
Merged

alexey-milovidov merged 28 commits into
masterfrom
fix-mutation-pruning-table-in-set

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #117113
Related: #110968
Related: #117115

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

Fix ALTER DELETE/ALTER UPDATE silently skipping rows when the predicate contains IN <table>.
The default-enabled optimize_mutations_with_partition_pruning evaluated that set at submission time
and narrowed the mutation's block_numbers, so a partition matching only the execution-time set was
left out while the mutation still reported is_done = 1.

Description

contains_deferred_set in MergeTreeData::getPartitionIdsPrunedByPredicate intends to leave every
deferred IN form unpruned — its own comment says so — but for the table form it only checked
right_argument->as<ASTTableIdentifier>(). A parsed IN some_table carries a plain ASTIdentifier;
only an already-resolved one is an ASTTableIdentifier (which derives from it). The analysis then
resolved the identifier to a prepared set and pruned with its submission-time contents.

That is the worst form to miss. An explicit subquery in a mutation predicate is rejected up front by
the pre-existing allow_nondeterministic_mutations validation ("ALTER UPDATE/ALTER DELETE statement
with subquery may be nondeterministic"), while a bare table identifier passes it — so the deferred-set
form users can actually run at default settings was exactly the one the guard let through.

Checking for ASTIdentifier covers both spellings, and nothing else can legitimately stand there: the
right-hand side of IN is a set, a tuple, a subquery, a table or a table function.

The existing 04909_mutation_partition_pruning_deferred_sets cannot catch this because it sets
validate_mutation_query = 0, and getPartitionIdsAffectedByCommands disables pruning entirely when
validation is off — the guard is never reached for the table form. New test
05075_mutation_partition_pruning_table_in_set asserts the resulting
block_numbers.partition_id directly, and that a literal enumeration is still pruned.


Workflow [PR]
Sync PR [sync-upstream/pr/117272]

Version info

  • Merged into: 26.12.1.101-master (included in 26.12 and later)

…for mutation pruning

Mutation partition pruning leaves a predicate with a deferred `IN` set unpruned, because the
pruning pass and the asynchronous mutation execution evaluate the set independently: rows in a
partition that matches only the execution-time set have no block number and escape the mutation,
while it is still reported `is_done = 1`.

The guard only recognised an `ASTTableIdentifier` on the right-hand side, but a parsed
`IN some_table` carries a plain `ASTIdentifier`; only an already-resolved one is an
`ASTTableIdentifier`. That is also the worst form to miss: an explicit subquery in a mutation
predicate is rejected up front by the `allow_nondeterministic_mutations` validation, while a bare
table identifier passes it - so the deferred-set form users can actually run at default settings
was exactly the one the guard let through.

Nothing else can stand there: the right-hand side of `IN` is a set, a tuple, a subquery, a table
or a table function, so any identifier names a table.

Closes: #117113
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [20ad298]

Summary: ✅


AI Review

Summary

The PR prevents mutation partition pruning from narrowing the scope of table-backed IN predicates, including sets reached through ALIAS columns. The current code addresses the earlier review findings, and the regression test checks both deferred sets and predicates that should remain prunable. No remaining actionable findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

The one-line fix looks correct and safely conservative for the spelling it targets, and since ASTTableIdentifier derives from ASTIdentifier no previously-guarded form is lost. I checked the sibling spellings against the same guard: all isNameOfInFunction variants, compound IN db.table, table functions on the right (covered by the non-literal ASTFunction branch), explicit subqueries (ASTSubquery check plus submission-time rejection), and the lightweight-update consumer, which reaches the same getPartitionIdsAffectedByCommands call — all covered.

One same-function sibling stays open after this merges: contains_deferred_set walks only the raw predicate AST, so a deferred set hidden behind a column definition is invisible to it while the pruning analysis deliberately expands such columns against the storage. The definition is creatable for the same parsing reason this PR fixes — a bare table identifier is not a subquery node, so the no-subqueries-in-column-defaults validation passes it. Verified on current master: with flag UInt8 ALIAS p IN keys, partitions 1 and 2 in the table, and keys containing only 1, ALTER TABLE t DELETE WHERE flag is accepted and records block_numbers.partition_id = ['1'] — the submission-time contents of keys. Today the mutation subsequently wedges on #117276 (the expanded in has no set scheduled for building, so execution retries a Not-ready Set logical error forever), so the escape is not yet silent; once that execution defect is fixed, a partition matching only the execution-time set contents will silently escape while is_done reaches 1. The fix pattern already exists in the sibling PR #117273 — the identifier-to-column-default recursion just needs to be applied to (or shared with) contains_deferred_set.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 20ad29813 with master e3a18a726 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 31 s compile time in total, 7 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 4, 2026
alexey-milovidov and others added 3 commits September 10, 2026 05:00
…red set

Address review: the pruning guard only inspected the raw predicate AST, while the
analysis below expands `ALIAS` columns against the storage
(`collectSourceColumns` with `keep_alias_columns = false`). A column default such
as `is_hit UInt8 ALIAS p IN keys` therefore carried a deferred set past the guard,
and `ALTER TABLE ... DELETE WHERE is_hit` was still pruned to the submission-time
contents of `keys`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…`ALIAS` carrier

`IAST::as` is an exact-type cast, not a `dynamic_cast`, so `as<ASTIdentifier>`
does not match an `ASTTableIdentifier` - and `MarkTableIdentifiersVisitor`
rewrites the node in place, including inside a column default expression the
storage metadata keeps. Spell out both forms.

Extend test 05075 with the `ALIAS` carrier the review asked for: a column
`is_hit UInt8 ALIAS p IN keys` must leave the mutation unpruned, while
`is_one UInt8 ALIAS p IN (1)` is a stable constant set and is still pruned.

The test also waits for the mutation entries with `SYSTEM SYNC REPLICA ... PULL`
before reading `system.mutations`: an entry becomes visible only after this
replica pulls it from ZooKeeper, which made the test flaky in CI (the second
mutation row was sometimes missing).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @zlareb1 thank you - the column-default escape you verified on master is now fixed in this PR rather than left for #117273: contains_deferred_set follows an identifier into its column default, so flag UInt8 ALIAS p IN keys no longer carries a deferred set past the guard, and 05075_mutation_partition_pruning_table_in_set covers that carrier with is_one UInt8 ALIAS p IN (1) as the negative control.

Your note that the definition survives the no-subqueries-in-defaults validation also explains a second defect: MarkTableIdentifiersVisitor rewrites the right-hand identifier in place inside the stored default expression, and IAST::as is an exact-type cast, so the guard has to list ASTIdentifier and ASTTableIdentifier explicitly - it does now. Details in the review thread reply.

Also fixed the CI flake in the new test: a mutation entry is visible in system.mutations only after this replica pulls it from ZooKeeper, so the test now waits with SYSTEM SYNC REPLICA ... PULL.

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: e11a5445-4cc9-489d-abc3-6d2261911140
  • MIRAI run: 09d6430d-6137-440b-997a-665c8a26bcb1
  • PR check IDs:
    • clickbench_210918_1791389887
    • clickbench_210931_1791389886
    • clickbench_210937_1791389886
    • tpch_adapted_1_official_210943_1791389886
    • tpch_adapted_1_official_210954_1791389887
    • tpch_adapted_1_official_210989_1791389886

alexey-milovidov and others added 2 commits September 24, 2026 13:41
…the deferred-set check

The deferred-set check in `getPartitionIdsPrunedByPredicate` looked up column
defaults by the raw identifier spelling, so `DELETE WHERE t.is_hit` missed the
`is_hit` `ALIAS` (which hides `p IN some_table`) while the analysis resolved the
qualified name all the same and pruned the mutation to the submission-time set.
Strip a `table.` / `database.table.` qualifier naming this table and also try
every name prefix, so that a subcolumn of such a column is followed as well.

Also document why an identifier on the right of `IN` is always a table here:
`AddDefaultDatabaseVisitor` qualifies it with the database, so a column there
(`x IN arr`) is rejected in mutation predicates and in column defaults alike.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits October 2, 2026 17:02
…ed-set check

A stored `DEFAULT`/`MATERIALIZED` column is read as it was written, so a
deferred set in its definition is not evaluated by either the pruning pass or
the mutation execution. Following it only lost pruning for a safe predicate.
Mirror `contains_nondeterministic_function` and add a regression for a
`MATERIALIZED` carrier.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A `MATERIALIZED` column with `IN some_table` cannot be inserted into at all
(#117276), so cover the stored
carrier with a `DEFAULT` column written explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117272&sha=88c4f5982fb5955ffe937976930c449b9a424b4f&name_0=PR&name_1=AST%20fuzzer%20(amd_debug%2C%20targeted%2C%20old_compatibility) (Not-ready Set is passed as the second argument for function 'in' inside FilterTransform, tracked in #118722) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #119664 (it closes #117276, which is this abort).

The aborting mutation comes from this PR's own test, unfuzzed: ALTER TABLE t_prune_in_table_alias DELETE WHERE is_hit, where is_hit is ALIAS p IN t_prune_in_table_keys. After the test's SYSTEM STOP REPLICATION QUEUES, the fuzzer ran SYSTEM START REPLICATION QUEUES variants, so the mutation actually executed. The abort is in the mutation of part 1_0_0_0 (query id b1d17437-...::1_0_0_0_1 in fatal.log).

This PR does not cause it. The same thing aborts on master (064b09a3, debug build) with a plain MergeTree, with the same stack as CI (FilterTransform.cpp:298 -> in.cpp:155):

CREATE TABLE keys (p UInt8) ENGINE = MergeTree ORDER BY p;
CREATE TABLE t (p UInt8, x UInt64, is_hit UInt8 ALIAS p IN keys) ENGINE = MergeTree PARTITION BY p ORDER BY x;
INSERT INTO keys VALUES (1);
INSERT INTO t VALUES (1, 1), (2, 2);
ALTER TABLE t DELETE WHERE is_hit;

With the Build (amd_debug) binary of #119664 (head 486cc1cc), the same script finishes the mutation (is_done = 1, only (2, 2) left) and nothing aborts. This failure can come back on this PR until #119664 is merged, because the test keeps the DELETE WHERE is_hit statement.

alexey-milovidov and others added 2 commits October 4, 2026 15:29
…ns in the deferred-set check

The deferred-set walk in `getPartitionIdsPrunedByPredicate` treated every identifier as a storage
column, including lambda parameters, so `arrayExists(x -> x = 1, arr)` with a column `x ALIAS p IN keys`
lost partition pruning. Mirror the lambda handling of the non-determinism check: skip the parameter
list, track bound names while visiting the body, and do not carry them into a followed column
definition. Cover both the shadowing case and a free name inside a lambda body in `05075`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
In the `DBReplicated` stateless run, `SYSTEM STOP REPLICATION QUEUES` stops only the local replica, so
another replica executed `ALTER TABLE t_prune_in_table_alias DELETE WHERE is_hit` and hit the
`Not-ready Set is passed as the second argument for function 'in'` exception of
#117276, aborting that server.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117272&sha=58900020280f2b4987a013dc1355d569ef7f21dc&name_0=PR&name_1=Stateless%20tests%20(amd_llvm_coverage%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%203%2F3)
PR: #117272

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. The Stateless tests (amd_llvm_coverage, s3 storage, DBReplicated, parallel, 3/3) abort had the same cause: in the DBReplicated run, SYSTEM STOP REPLICATION QUEUES stops only the local replica, so another replica ran DELETE WHERE is_hit on t_prune_in_table_alias and hit #117276. 05075 is now tagged no-replicated-database (1404e1f). The AST fuzzer can still start the queues and hit the same abort until #119664 is merged.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117272&sha=43f81d75e08cf8518c9466936c9fa7f293fffa95&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20s3%20storage%2C%20DBReplicated%2C%20sequential%29 (03821_drop_workload_during_query_race, exception from RequestQueue::enqueueRequest in stdout, 3/34 reruns failed) and provide a fix in a separate PR. If the fix is already in progress, link it here. The Upgrade check crash in GraceHashJoin::addBuckets is fixed on master by #126204, which I merged into this branch.

@groeneai

Copy link
Copy Markdown
Collaborator

Already fixed by #126345 (merged 2026-10-19 10:34Z), so no new PR is needed.

The stack is the expected INVALID_SCHEDULER_NODE thrown in the query thread (RequestQueue::enqueueRequest <- CPULeaseAllocation constructor <- PipelineExecutor::allocateCPU) when DROP WORKLOAD races the query. The test filtered the client output line by line with grep -v, so the multi-line stack trace of that expected error leaked into stdout. #126345 drops the whole output of a query that failed with an expected error.

The 43f81d7 run (2026-10-18) was built before the fix; the new head 09b45db already contains it. Since the merge: 667 master runs with 3 failures, all on commits without the fix, and the 2 PR failures were re-runs of workflows created before the merge.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. Confirmed: the head 09b45dba contains #126345, and its CI run is green, so nothing more is needed here for 03821_drop_workload_during_query_race.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of the CI failures on da1dd1d:

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of the CI failures on d95721b:

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status on e085e92: public CI is green. The only red check is CH Inc sync (tests failed (1 new, 4 known)). Its failures are all in areas this PR does not touch: test_storage_iceberg_with_spark/test_compaction_file_size.py::test_compaction_splits_a_file_above_the_upper_threshold (MSan, TSan), test_shared_merge_tree_lightweight_snapshot/test.py::test_snapshot_of_part_with_zero_object_file (TSan), 05318_file_log_one_bad_file and 03742_nested_loop_join_long. I reran the failed jobs of the sync PR.

alexey-milovidov added a commit that referenced this pull request Oct 31, 2026
…deferred set

Now that a mutation through `flag ALIAS p IN keys` executes instead of throwing, the partition
pruning of `getPartitionIdsPrunedByPredicate` must not narrow it to the partitions matching the
submission-time contents of `keys`: the set is built again when the mutation executes, so rows in a
partition matching only then would escape the mutation while it reports `is_done = 1`.

Follow an identifier of the predicate into its `ALIAS`/`EPHEMERAL` column definition when looking for
a deferred set, and treat a plain `ASTIdentifier` on the right of `IN` (the parsed form of `IN table`)
as one. This is the guard of #117272, included here so
this change does not depend on it landing first.

The new test changes the right-hand side between the submission and the execution of a mutation on
a partitioned `ReplicatedMergeTree` and checks that the rows of the newly matching partition are deleted.

Related: #117272
Related: #117113

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of the CI failures on b882000:

I merged master (20ad298) to refresh the branch. There are no unresolved review threads.

@alexey-milovidov alexey-milovidov left a comment

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.

Acceptable.

@alexey-milovidov alexey-milovidov self-assigned this Nov 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 20, 2026
Merged via the queue into master with commit 453ba8d Nov 20, 2026
196 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-mutation-pruning-table-in-set branch November 20, 2026 21:28
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 20, 2026
@stresshouse

stresshouse Bot commented Nov 20, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

No performance changes are attributed to this PR. It only changes how mutation partition pruning detects deferred IN sets (MergeTreeData::getPartitionIdsPrunedByPredicate) and adds a test, and none of the benchmark SELECT queries run that code. The one flagged row, clickbench Q10 (+17.9%, 95 ms to 112 ms), was correctly kept at not_sure: it sits inside master's current 83–115 ms range and has a noisy history. Nothing in the diff points to this delta, so the PR shows no regressions or improvements.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 10 not_sure 95 112 +17.9% <0.0001 aggregation: Q10 is a read-only GROUP BY with COUNT(DISTINCT) and never reaches mutation partition pruning, the only code this PR changes. The 112 ms median falls inside master's current 83–115 ms range, and this query is noisy on master.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: e449eb6d-8a1c-4979-a6b4-7d0e5b284084
  • MIRAI run: f17daab7-3a1e-42c7-9024-fbc3dd082a8c
  • PR check IDs:
    • clickbench_559135_1795213360
    • clickbench_559141_1795213360
    • tpch_adapted_1_official_559147_1795213360
    • tpch_adapted_1_official_559170_1795213360

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). 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

4 participants