Skip to content

Cherry pick #119337 to 26.10: Do not prune a part by statistics while an alter mutation is pending - #128828

Merged
PedroTadim merged 34 commits into
backport/26.10/119337from
cherrypick/26.10/119337
Nov 4, 2026
Merged

PedroTadim merged 34 commits into
backport/26.10/119337from
cherrypick/26.10/119337

Conversation

@robot-clickhouse-ci-2

Copy link
Copy Markdown
Contributor

Original pull-request #119337

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

alexey-milovidov and others added 30 commits September 10, 2026 20:01
A pending `ALTER MODIFY COLUMN` is applied on the fly, so a read already returns the converted values,
while the part's statistics still describe the values as they were written. Statistics-based part
pruning compared the predicate against those stale statistics and dropped the part, so

    CREATE TABLE t (x Float64 STATISTICS(basic), s String) ENGINE = MergeTree ORDER BY tuple();
    SYSTEM STOP MERGES t;
    INSERT INTO t VALUES (10.5, 'a'), (11.5, 'b');
    ALTER TABLE t MODIFY COLUMN x Int64 SETTINGS alter_sync = 0;
    SELECT x FROM t;                 -- 10, 11: the read is already converted
    SELECT count() FROM t WHERE x = 10;  -- 0, the part is pruned by the range [10.5, 11.5]

returned no rows for the whole lifetime of the pending mutation, at default settings and with no error.

`filterPartsByStatistics` gated on `hasDataMutations` and `hasPatchParts`, but an `ALTER MODIFY COLUMN`
is neither: it is a `READ_COLUMN` alter mutation. Add `hasAlterMutations` to the gate, which is
exactly what the neighbouring gate for the top-k minmax index (`partHasStaleTopKIndex`) already checks.
The gate stays as coarse as the two conditions next to it - any pending alter mutation disables
statistics pruning for the query, rather than only one that touches a column with statistics.

Closes: #116627
… mutations

A pending `DROP COLUMN` is a metadata mutation, and a column with the dropped
name can be added again right away. `AlterConversions` then makes a read return
the new column's default, while `IMergeTreeDataPart::loadStatistics` still
loads the dropped column's statistics under that name, so `WHERE b = 7` on the
re-added `b` pruned the old part by the stale `[1000, 1099]` range and returned
0 rows. Add `hasMetadataMutations` to the gate in `filterPartsByStatistics`.

`partHasStaleTopKIndex` had the same blind spot: after `DROP INDEX`, `DROP
COLUMN`, `ADD COLUMN ... DEFAULT`, `ADD INDEX` with the same names, the part
still holds the minmax index built over the dropped values, and `ORDER BY b
DESC LIMIT 1` picked the wrong part. Include metadata mutations in the gate and
treat the index as stale when one of its columns is dropped by a pending
mutation (`isColumnDropped`); a plain `RENAME COLUMN` keeps the index valid.

Both scenarios are added to `05200_statistics_pruning_pending_alter` and were
reproduced on the previous head of this branch before the fix.

Addresses the review thread on
#119337

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ending metadata mutations

Two gaps left by the previous fence, both from the `clickhouse-gh` review:

- The query condition cache is keyed by the part name, which a pending `ALTER MODIFY COLUMN`
  (alter mutation) or `DROP COLUMN` / `RENAME COLUMN` (metadata mutation) does not change.
  `filterPartsByQueryConditionCache` only bailed out on data mutations and patch parts, so an
  entry recorded for a dropped column pruned marks of a re-added column with the same name.
  Fence the read side on alter and metadata mutations too, and keep the write sides in
  `ReadFromMergeTree` symmetric.

- `canUseIndex` only knows about columns updated on the fly, so every skip-index path (index
  analysis, skip indexes on data read, direct read from a text index, the top-k minmax) used an
  index file built over a column that is dropped or renamed by a pending mutation, after a new
  column with the same name and an index with the same name were added. Add
  `AlterConversions::getColumnsInvalidatingIndexes` (updated columns plus every name touched by a
  pending drop or rename) and pass it to `canUseIndex` from all per-part callers; this replaces
  the top-k-only `isColumnDropped` check.

Extend `05200_statistics_pruning_pending_alter` with the regular skip-index case and the query
condition cache case.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…nmax on pending metadata mutations

`IndexReadRangesRefiner` (with `use_indexes_refiner_in_read_pools = 1`) still built the skip-index
result from `getAllUpdatedColumns`, and `MergeTreeSkipIndexReader::read` built the minmax for the
read-time TopK threshold without any staleness check. Both could use an index file built over a
column that a pending `DROP COLUMN` / `RENAME COLUMN` rebound to a new one. Pass
`getColumnsInvalidatingIndexes` to the refiner and check `canUseIndex` for the TopK minmax.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… part has pending alter mutations

`mergeTreeProjection` reads clear the mutations snapshot, so pending alter and metadata
mutations (`MODIFY COLUMN`, `DROP COLUMN`, `RENAME COLUMN`), which the parent read applies
on the fly via `AlterConversions`, are not applied to the projection. Under a row policy the
projection could show stale values. Refuse the read for parts that still have on-the-fly
mutation commands. The check is per part, because the snapshot counters
(`hasAlterMutations`) also include already finished mutations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp
…ROP COLUMN`

Cover the metadata-mutation arm of `getColumnsUpdatedOnFly` in
`optimizeDirectReadFromTextIndex.cpp`: after `DROP INDEX; DROP COLUMN s; ADD COLUMN s; ADD INDEX`
with the drop still pending, `hasToken` on the re-added column must not be answered from the
postings built over the dropped one. Without that arm the test returns 0 rows instead of 10.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…umnsInvalidatingIndexes`

`addMutationCommand` normalizes `rename_map` and `dropped_columns`: chained
renames `A -> B; B -> C` collapse into one `A -> C` entry, and a drop after a
rename is recorded under the original name. Rebuilding the invalidating set
from them lost the intermediate name `B`. Collect every name used by a pending
`RENAME COLUMN` or `DROP COLUMN` command separately, as written in the command.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ype differs

A read converts the values of a column stored in a part with an old type to the
current type (`IMergeTreeReader::performRequiredConversions`) regardless of the
mutations snapshot: with `apply_mutations_on_fly = 0` the pending `MODIFY COLUMN`
is not in the snapshot, and after `KILL MUTATION` it is gone. In both cases the
part's statistics still describe the old values and could prune matching rows.
Ignore the statistics of such columns per part, and cover both cases in the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
The counters of the mutations snapshot (`hasAlterMutations`, `hasMetadataMutations`) also include
finished mutations retained for `system.mutations` (`finished_mutations_to_keep`), so a completed
`DROP COLUMN` disabled statistics pruning and the query condition cache until it was evicted.

Add `MergeTreeDataSelectExecutor::partHasPendingAlterOrMetadataMutations` and
`hasPendingAlterOrMetadataMutations`, which look only at the commands newer than each part
(`getOnFlyMutationCommandsForPart`), and use them in `filterPartsByStatistics` (per part), in
`filterPartsByQueryConditionCache` and in both write-side gates of `ReadFromMergeTree`. Extend the
test to assert that statistics pruning and the query condition cache are used again after the
mutation materialized.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…materialize_statistics_on_insert`

The test randomizer can set `materialize_statistics_on_insert = 0`, in which case the part of
`t_05200_done` has no statistics and the assertion that it is pruned by statistics fails before
any mutation happened. Force materialization of statistics on that insert.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119337&sha=latest&name_0=PR
PR: #119337

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tistics

`getStatisticsMinMaxAggregates` rejected the optimization whenever the
mutations snapshot had any alter or metadata mutation, but the snapshot
counters also include finished mutations kept for `system.mutations`, so one
finished `DROP COLUMN` disabled the optimization until newer mutations evicted
it. Check `partHasPendingAlterOrMetadataMutations` per part instead and read
the affected parts normally, and also skip parts whose stored column type
differs from the metadata.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
…stics_min_max_aggregation_after_finished_mutation`

The `minmax` statistics type is now deprecated and logs a warning on table creation, which
made the test fail in Fast test with "having stderror".

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119337&sha=latest&name_0=PR&name_1=Fast%20test
#119337

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ng type changes

The check that a part stores a column with the same type as the current
metadata rejected representation-preserving changes as well, e.g. extending
`Enum8('a' = 1)` to `Enum8('a' = 1, 'b' = 2)`. Such an alter schedules no
mutation, so the old parts kept losing the statistics-only `min`/`max` answer
and the part pruning by statistics until they were rewritten. Both places now
use `isRepresentationPreservingConversion`, already used for skip indexes, which
is moved out of the anonymous namespace.

In `filterPartsByStatistics`, check only the required columns, with their
current types resolved once for all parts. `getEstimates` may return the
estimates of every column of the part, and looking up both types of each of
them for every part made the queries to wide tables slower (`lot_of_subcolumns`,
`merge_tree_huge_pk`, `json_typed_path_subcolumn_lookup` in the performance
comparison).

Add a test for an extended enum keeping the optimization and the pruning, and
for a killed narrowing alter returning the converted `min`/`max` values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…istics of a part with a stale column type

`05453_statistics_pruning_pending_rename` covers the repro of #117323: with a pending `DROP COLUMN x, RENAME COLUMN y TO x`, statistics-based part pruning and `min`/`max` from statistics must not use the estimate of the dropped column stored under `x`.

`05454_statistics_min_max_stale_part_type` ports the cases of #126076 that the existing tests do not cover: `min`/`max` from statistics while a narrowing `MODIFY COLUMN` is pending with `apply_mutations_on_fly = 0` (so it is not in the mutations snapshot), after it is killed, and a `Decimal` scale change, which keeps the type of `Field`.

Both tests pass with the CI build of 4f7649a and fail with a build without this PR.
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Nov 3, 2026
Resolve conflicts against the release branch: `makeBlockWithMinMaxFromStatistics` has no `context` parameter there, `filterPartsByStatistics` loads statistics in a plain loop (no `loadStatisticsOfPartsInParallel`), and `partHasStaleTopKIndex` has no masking-policy gate. The per-part pending-mutation and representation-preserving-conversion checks of #119337 are applied in the release-branch shape.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim
PedroTadim merged commit 6d9d047 into backport/26.10/119337 Nov 4, 2026
1 check passed
@PedroTadim
PedroTadim deleted the cherrypick/26.10/119337 branch November 4, 2026 12:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants