Skip to content

Do not prune a part by statistics while an alter mutation is pending - #119337

Merged
alexey-milovidov merged 32 commits into
masterfrom
fix-statistics-pruning-pending-alter-116627
Oct 30, 2026
Merged

alexey-milovidov merged 32 commits into
masterfrom
fix-statistics-pruning-pending-alter-116627

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

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 to CHANGELOG.md):

Fix silently missing rows when a query filters on a column whose ALTER MODIFY COLUMN or DROP COLUMN is still a pending on-the-fly mutation: statistics-based part pruning, skip indexes (including the top-k minmax index) and the query condition cache described the values as they were written, and dropped parts or granules the query had to read.

Documentation entry for user-facing changes

...

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 (use_statistics_for_part_pruning = 1 since 26.4) 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 alter (and metadata, see below) mutations are checked per part, through the commands newer than the part (MergeTreeDataSelectExecutor::partHasPendingAlterOrMetadataMutations): the snapshot counters also include finished mutations kept for system.mutations, which must not disable pruning for the parts they were already applied to. A part with such a pending mutation is not pruned by statistics, whichever column the mutation touches. The query condition cache gates use the same check over the selected parts.

The review found a second blind spot of the same kind: a pending DROP COLUMN is a metadata mutation, and a column with the dropped name can be added again right away. A read then returns the new column's default, while the part's statistics are still loaded under that name for the dropped column, so WHERE b = 7 on the re-added b pruned the part and returned 0 rows. The statistics gate now also checks hasMetadataMutations. partHasStaleTopKIndex had the same problem after DROP INDEX, DROP COLUMN, ADD COLUMN ... DEFAULT, ADD INDEX with the same names: the part keeps the minmax index built over the dropped values, and ORDER BY b DESC LIMIT 1 picked the wrong part. It now includes metadata mutations in its gate.

A second review pass found two more paths of the same kind, both fixed:

  • Every skip-index path (index analysis, skip indexes on data read, direct read from a text index, the top-k minmax) consulted only canUseIndex, which knows about columns updated on the fly but not about metadata mutations, so after DROP INDEX idx; DROP COLUMN b; ADD COLUMN b ...; ADD INDEX idx b a WHERE on b was pruned by the index file built over the dropped b (0 rows instead of 11 with use_skip_indexes_on_data_read). The new AlterConversions::getColumnsInvalidatingIndexes returns the updated columns plus every name touched by a pending DROP COLUMN or RENAME COLUMN, and all per-part canUseIndex callers pass it. An index on a column renamed by a still-pending mutation is therefore not used for that part until the rename is materialized (conservative: which column a part's index file was built over is not recorded).
  • The query condition cache is keyed by the part name, which a pending alter or metadata mutation does not change, so an entry recorded for a dropped column pruned marks of the re-added one. filterPartsByQueryConditionCache now also bails out on alter and metadata mutations, and the write sides in ReadFromMergeTree are gated the same way.

A pending DROP INDEX idx followed by ADD INDEX idx on another column (no column mutation involved) is a separate, pre-existing bug and is not fixed here.
Related: #121171

New test: 05200_statistics_pruning_pending_alter, covering all of these scenarios. Verified in both directions, and a differential run of the statistic/on_fly/mutation/alter_modify/prune stateless tests (341 tests) shows no new failures.

Closes: #116627
Closes: #117323

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.922-master (included in 26.11 and later)

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
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [86dccbc]

Summary: ✅


AI Review

Summary

PR #119337 prevents statistics, skip indexes, and the query condition cache from pruning rows using values invalidated by pending column mutations. It also guards projection reads under row policies and preserves statistics optimizations after completed mutations and representation-preserving type changes. Reviewed head: 86dccbcd3b5fd05f19a676412588e47de9c393fc. Prior findings are addressed in the current code; no new actionable findings remain. All seven added regression tests match their references with the PR's 9fa85d54 ARM CI binary, and the current Praktika reports contain no failed tests.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 10, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 86dccbcd3 with master bee6deac1 (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.

Object file sizes

29 object files changed (+50.59 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/StorageFromMergeTreeProjection.cpp.o 280.91 KiB 300.07 KiB +19.16 KiB (+6.82%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp.o 1.11 MiB 1.13 MiB +16.52 KiB (+1.45%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Upgrade check (amd_release) is red for two reasons that have nothing to do with this change, which only skips statistics-based part pruning while an alter mutation is pending:

  • Logical error: 'Got read request from replica 1 for unknown stream test_5.t_mt_index_rp.' — the signature tracked in the issue below, from the parallel-replicas read coordinator.
  • Code: 40. Checksums of parts ... logged by a MergeFromLogEntryTask, which the upgrade check picks up as an error message in the server log.

Related: #110518

alexey-milovidov and others added 2 commits September 18, 2026 04:44
… 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]>
alexey-milovidov and others added 4 commits September 24, 2026 05:32
…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]>
alexey-milovidov and others added 3 commits October 4, 2026 14:34
… 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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: 04604_adaptive_aggregator_compaction timed out in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119337&sha=9fc0534a68507a1def6c7838df1a24ae0f864273&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 (reproducible only with the randomized settings, passes 107/107 without them; unrelated to this PR, which changes part pruning under pending mutations), and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the 04604_adaptive_aggregator_compaction timeout under randomized settings; I'll follow up here with a separate PR (or my findings) shortly.

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator

Fix: #125345

Root cause: the MergeTree randomizer drew index_granularity = 7 (with min_bytes_for_wide_part = 1073741824), so the 200,000-row table became one compact S3 part with 28,572 granules, and with the filesystem cache off each multi-column scan issued about one S3 GET per granule (263,039 GETs, 595.6 s before the kill). The PR adds a -- Random settings limits: floor for index_granularity / index_granularity_bytes to that test, the same floors the runner already uses for long tests and slow builds.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only CI failure, 05210_lightweight_update_materialized_cte_in_ignore in Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119337&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel)), is not related to this PR. It is the known UNKNOWN_TABLE for a materialized CTE referenced twice under parallel replicas: #112642, with a fix in progress in #123121. I merged master to refresh the branch.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 All 22 red checks on 3c53e90 come from one failure: Build (arm_release) (https://github.com/ClickHouse/ClickHouse/actions/runs/38440025862/job/115678305844). Its log stops at 22:50:38 in the middle of building contrib sources, with no compiler error, but the job did not finish until 23:05. That pattern means the runner was lost. Every other build passed, including arm_darwin, and all stateless and integration test jobs passed. I merged the latest master (clean merge, builds locally) to start a fresh CI run.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (ac50bde); the PR's translation units compile. The only failure on e260ffd, 05227_mutate_part_ahead_of_table_metadata_version_mergetree in Fast test, is unrelated: it fails in Fast test for many other PRs (2026-10-27/28), and it is being fixed in #127925. The Finish Workflow failure only happened because Bugfix validation was dropped after Fast test failed.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (86dccbc); ReadFromMergeTree.cpp and MergeTreeDataSelectExecutor.cpp compile. The only real failure on 9fa85d5, Logical error: 'ReadBuffer is canceled. Can't read from it.' (STID: 2508-2bbd) in Stateless tests (amd_debug, parallel) (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119337&sha=9fa85d54d40a2bf70c251b204c112ea6f1376888&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29), comes from DB::ask in the embedded client (ClientBase::initOutputFormat), which this PR does not touch. It is being fixed in #128090. The Finish Workflow failure only reflects that the Bugfix validation jobs were dropped after that failure.

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

Looks like a clean bugfix.

@alexey-milovidov alexey-milovidov self-assigned this Oct 30, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 30, 2026
Merged via the queue into master with commit 3535c58 Oct 30, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-statistics-pruning-pending-alter-116627 branch October 30, 2026 13:23
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 30, 2026
alexey-milovidov added a commit that referenced this pull request Oct 31, 2026
#119337 landed on master with a broader fix for the same
class of bugs: statistics pruning, skip indexes (including the top-k minmax index), the query condition
cache and direct reads from text indexes are now disabled for a part with any pending alter or metadata
mutation (`partHasPendingAlterOrMetadataMutations`, `AlterConversions::getColumnsInvalidatingIndexes`).
The conflicts are resolved in favour of master, and the per-column variants of these checks from this
branch (`getColumnsWithStaleIndexes`, `changesColumnIdentity`, `partChangesColumnIdentity`) are dropped
as subsumed. The fix for the trivial `count` from sparse-column defaultness statistics is kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@fm4v fm4v removed pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR v26.10-must-backport labels Nov 3, 2026
alexey-milovidov added a commit that referenced this pull request Nov 4, 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 added a commit that referenced this pull request Nov 4, 2026
Cherry pick #119337 to 26.10: Do not prune a part by statistics while an alter mutation is pending
alexey-milovidov added a commit that referenced this pull request Nov 6, 2026
`Bugfix validation (functional tests)` requires every new test to fail on `master`. The tests
for statistics-based part pruning, skip indexes, the query condition cache (including top-k)
and direct reads from text indexes pass there, because those paths were fixed on `master` by
#119337, which has its own tests. They are removed
from this PR, which is now only about `optimize_trivial_count_with_sparsity_filter`.

The positive case of `05361_trivial_count_sparsity_pending_rename_other_column` (a pending
metadata mutation of another column keeps the rewrite) is moved into
`05227_trivial_count_sparsity_pending_rename`, which fails on `master`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117814&sha=latest&name_0=PR&name_1=Bugfix%20validation%20(functional%20tests%2C%20amd64)
#117814

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
…ition cache

ClickHouse#119337 added `hasPendingAlterOrMetadataMutations`, which stops reading and writing the
query condition cache while an alter or metadata mutation is pending for one of the read
parts. It covers what `hasPendingMetadataMutations` was added for (a pending `DROP COLUMN`
or `RENAME COLUMN` that `KILL MUTATION` can leave unmaterialized), and it ignores the
finished mutations the snapshot keeps for `system.mutations`, which made our snapshot-level
check disable the cache after any `DROP COLUMN` until the mutation was evicted. So drop
`hasPendingMetadataMutations` from the read side and both write sides.

Its last user was `isQueryConditionCacheAllowed`, which also checked it because projection
analysis reads projection parts with an empty mutations snapshot. Since ClickHouse#118585 a part with a
pending metadata mutation on a column the projection holds or the read needs is read from the
parent part, so projection analysis does not consult the cache for it, and the getter is back
to master's form.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
… in 05458

Since ClickHouse#119337 the query condition cache is skipped while an alter mutation is pending for a part,
so the existing `DEFAULT now64 for NULL` cases pass on master. After `KILL MUTATION` of the
`MODIFY COLUMN` the part keeps its `Nullable` column, nothing is pending, and every read still
replaces the NULLs with `now64(3)`: on master the cached query returns 0 rows instead of 100000.
The new case fails when `IMergeTreeReader::performRequiredConversions` does not record the
non-deterministic conversion output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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

7 participants