Skip to content

Do not prune a part by statistics while a RENAME COLUMN is pending - #117814

Open
alexey-milovidov wants to merge 57 commits into
masterfrom
statistics-pruning-pending-rename-117323
Open

alexey-milovidov wants to merge 57 commits into
masterfrom
statistics-pruning-pending-rename-117323

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

While a RENAME COLUMN is still a pending on-the-fly mutation, or a pending DROP COLUMN x is followed by adding a column named x again, reads apply the metadata mutation, but the per-column num_defaults in serialization.json stay keyed by the names the columns have on disk. The trivial count() rewrite of optimize_trivial_count_with_sparsity_filter answers SELECT count() FROM t WHERE x = 0 from those counters, so it could count another column's defaults, or the defaults of the dropped data instead of the re-added column.

MergeTreeData::getColumnDefaultnessStats now takes the storage snapshot of the query's table expression and uses its parts and its mutations snapshot, which are exactly what the row scan of the same query reads. It declines the rewrite for a part whose pending DROP COLUMN or RENAME COLUMN in that snapshot touches the requested column (AlterConversions::getColumnsInvalidatingIndexes). A mutation that finishes or is removed from the history after the query's analysis (finished_mutations_to_keep, KILL MUTATION, reinitialization of the replication queue) does not change what the query reads, so it cannot change the stats either. This also covers transactions, because the snapshot holds the parts visible to the transaction.

The stats also honor the block-number cutoff of a lightweight update (Context::getPartitionIdToMaxBlock), the same as the row scan does: a subquery of an UPDATE no longer counts the defaults of a part inserted after the update allocated its block number.

The same bug class in statistics-based part pruning, skip indexes (including the top-k minmax index), the query condition cache and direct reads from text indexes was fixed on master by #119337. This branch's own changes for those paths, and their tests, were dropped in favour of it when merging master.

Closes: #117323
Related: #119337

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

Fixed a wrong result of SELECT count() ... WHERE x = <default> (optimize_trivial_count_with_sparsity_filter) while a RENAME COLUMN or DROP COLUMN + ADD COLUMN of x is still a pending mutation: the count used the defaultness statistics stored under the on-disk column name, which describe another column's data.

🤖 Generated with Claude Code


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

While a `RENAME COLUMN` is still a pending on-the-fly mutation, reads apply the rename and
return the other column's values, but the part's statistics are stored under the names the
columns have on disk. `filterPartsByStatistics` looked an estimate up by the queried name
and got a different column's range, pruning parts that hold matching rows:

    ALTER TABLE t DROP COLUMN x, RENAME COLUMN y TO x SETTINGS alter_sync = 0, mutations_sync = 0;
    SELECT count() FROM t WHERE x = 100;  -- 0, and 1 with use_statistics_for_part_pruning = 0

A rename is a metadata mutation and enters neither `hasDataMutations` nor
`getAllUpdatedColumns`, so the existing gate did not see it. A part whose read renames
anything is now left unpruned; parts without a pending rename are pruned as before.

Closes: #117323
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [64d5f8a]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR validates sparse-count statistics against the query's captured parts and mutation state, preventing stale counts during column renames, same-name re-adds, and mutation cleanup. One blocker remains in the new replicated cutoff filter: with select_sequential_consistency = 1, it can count a different set of partitions from the row scan and persist a different lightweight-update result.

Findings

❌ Blockers

  • src/Storages/StorageReplicatedMergeTree.cpp:6604: Replicated statistics and row reads combine partition cutoffs differently. The base filter removes every partition absent from the update map. However, readLocalSequentialConsistencyImpl at lines 6490–6499 retains quorum-map partitions absent from that map and only clamps matching entries. With one zero-valued row in each of two partitions, UPDATE t SET y = (SELECT count() FROM t WHERE x = 0) IN PARTITION 1 WHERE p = 1 under select_sequential_consistency = 1 consequently stores y = 1 with the rewrite and y = 2 with a scan, by source trace. Share the combined-cutoff construction with the reader, or decline the rewrite for this combination.
Tests
  • ⚠️ Add one stateless regression with two existing partitions of a ReplicatedMergeTree, exact defaultness statistics, a partition-scoped lightweight update, and select_sequential_consistency = 1. Compare the stored scalar-count result with the rewrite enabled and disabled. 05872 covers only plain MergeTree and cannot expose the different replicated map-combination rule.
Missing context / blind spots
  • ⚠️ The divergent counts above were established by tracing the current source, without local SQL execution; this review job has no ClickHouse binary. Run the focused replicated regression to verify the complete query path. The current Fast test report skips 05872 and the failpoint-based snapshot regressions.
Final Verdict

Status: ❌ Block

Make replicated statistics and row reads use identical partition cutoffs and add the focused regression.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 64d5f8a2d with master cb694c085 (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

222 object files changed (+56.58 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.74 MiB 4.76 MiB +20.61 KiB (+0.43%)

716 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

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 10, 2026 13:23
`filterPartsByStatistics` skipped a part only when a pending metadata
mutation renamed a column, but the same stale-statistics mismatch is
reachable when a pending `DROP COLUMN x` is followed by adding a column
named `x` again: reads treat the on-disk `x` as missing and fill the new
default, while `getEstimates` still returns the estimate stored for the
dropped column. A predicate such as `WHERE x = <new default>` then
pruned the part and silently lost rows.

Extend the guard to parts whose `AlterConversions` record any dropped
column, exposed through the new `AlterConversions::getDroppedColumns`.

Verified with a control binary that keeps only the rename half of the
guard: the new re-add case returns `0` instead of `2` there.

The test also moves to a free number (`05072` was taken by
`05072_limit_after_json_ast_invariants` on master) and pins
`materialize_statistics_on_insert` on its inserts - the settings
randomizer turned it off and the `Parts: 0/1` assertion of the positive
pruning case then had no statistics to prune with.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits September 18, 2026 02:22
…e` robust to parallel replicas

Under the ParallelReplicas stateless configuration the `EXPLAIN` row came back with a tree
prefix, so `trimLeft` left a box-drawing character in front of `Parts: 0/1` and the test failed
reproducibly. Extract the `Parts: N/M` token itself instead.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117814&sha=c319d28efe14cd8a88e2a6c2055ace519f2868f4&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
PR: #117814

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ion is pending

Address review: `optimize_trivial_count_with_sparsity_filter` answers `SELECT count() FROM t WHERE x = 0`
from the per-column `num_defaults` in `serialization.json`, which is keyed by the on-disk column names.
`MergeTreeData::getColumnDefaultnessStatsUnavailableReason` rejected pending patch, data and alter
mutations, but not metadata mutations. After a pending `DROP COLUMN x, RENAME COLUMN y TO x` or
`DROP COLUMN x, ADD COLUMN x`, reads already expose the new column while the rewrite still summed the
dropped column's counter, returning `2` where the answer is `0` and vice versa (reproduced with a
binary without the fix). Both overloads now return the new `MetadataMutations` reason.

Test: `05227_trivial_count_sparsity_pending_rename`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 2 commits September 24, 2026 01:38
…` is pending

Implicit minmax indices (`add_minmax_index_for_numeric_columns`) are named after their column, so
after a pending `DROP COLUMN x, ADD COLUMN x ... DEFAULT d` or `DROP COLUMN x, RENAME COLUMN y TO x`
the index file found by name in an old part was built over the dropped data, while reads already
return the new default or the renamed column. The skip-index, top-k granule selection, read-time
top-k threshold and direct text index read paths only checked `getAllUpdatedColumns`, which these
metadata mutations do not populate, so `WHERE x = d` could drop the only granule and
`ORDER BY x LIMIT n` could return a wrong row.

Add `AlterConversions::getColumnsWithStaleIndexes` (updated columns plus both names of pending
renames and dropped columns) and use it in all `canUseIndex` call sites. `partHasStaleTopKIndex`
now also looks at metadata mutations, and the read-time top-k threshold check in
`MergeTreeSkipIndexReader::read` now runs `canUseIndex` at all (it did not check pending updates
either).

Addresses the `clickhouse-gh` review on #117814

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/PRs/117814/857382bf4bb84e01e52d773a2e8a8a97c11d0f2f/pr/ast_fuzzer_amd_debug_targeted_old_compatibility/logical_error_unexpected_return_type_from_a._expected_b._got_c._action_stid_1611_3b3d/reproduce_commands.sql and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is not caused by this PR: this PR does not touch the read path, and the same result comes from a binary built from another branch without this PR's changes. The targeted fuzzer found it by mutating this PR's test table. Minimal repro (LOGICAL_ERROR Unexpected return type from assumeNotNull. Expected Int64. Got Int16):

CREATE TABLE t (id Int64, x Nullable(Int64)) ENGINE = MergeTree ORDER BY tuple();
SYSTEM STOP MERGES t;
INSERT INTO t VALUES (1, 1), (2, 2);
ALTER TABLE t DROP COLUMN x, ADD COLUMN x Int16 SETTINGS alter_sync = 0, mutations_sync = 0;
ALTER TABLE t MODIFY COLUMN x Nullable(Int64) SETTINGS alter_sync = 0, mutations_sync = 0;
SELECT groupArray(x) FROM t;

The same goes for the BuzzHouse (amd_tsan) failure AST subtree not found in children (STID: 1218-27e6), which has also failed on other PRs recently: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117814&sha=857382bf4bb84e01e52d773a2e8a8a97c11d0f2f&name_0=PR&name_1=BuzzHouse%20%28amd_tsan%29

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Not caused by this PR, and not new: this is the pending-drop conversion defect of #116416, and the fix in progress is your own #118585 ("Do not convert a column a pending mutation drops"), which patches exactly the frame this aborts in. So no separate PR from me.

x is dropped by a pending mutation, so neither reader reads it from the part (MergeTreeReaderCompact.cpp:84 and MergeTreeReaderWide.cpp:130 skip it on isColumnDroppedByPendingMutation) and the value comes from the current metadata: the re-added column's Int16 default. IMergeTreeReader::performRequiredConversions then still consults the type the part carries, Nullable(Int64), and builds the conversion from it, so assumeNotNull is declared to return Int64 and is handed an Int16 column:

Logical error: 'Unexpected return type from assumeNotNull. Expected Int64. Got Int16. Action:
FUNCTION assumeNotNull(x :: 0) -> assumeNotNull(x) Int64 : 4,
input block structure:x Nullable(Int64) Int16(size = 2)'

ExpressionActions.cpp:696 <- inplaceBlockConversions.cpp:284 <- IMergeTreeReader.cpp:518 <- MergeTreeReadersChain.cpp:480

#118585 puts if (isColumnDroppedByPendingMutation(pos)) continue; immediately above that columns_to_read[pos] read, so for this column no conversion is built at all.

It still reproduces on master (95a6488a, debug), with the last statement of your repro removed:

CREATE TABLE n (id Int64, x Nullable(Int64)) ENGINE = MergeTree ORDER BY tuple();
SYSTEM STOP MERGES n;
INSERT INTO n VALUES (1, 1), (2, 2);
ALTER TABLE n DROP COLUMN x, ADD COLUMN x Int16 SETTINGS alter_sync = 0, mutations_sync = 0;
SELECT groupArray(x), sum(x) FROM n;

Both mutations are still pending there and the part still carries x Nullable(Int64); the debug server takes signal 6.

Your repro as posted returns [] on master today: MODIFY COLUMN x Nullable(Int64) restores the requested type to the type the part carries, column_in_part.type->equals(...) holds, and no conversion is built. Worth knowing before that sequence becomes a regression test.

One gap in #118585 as it stands: 05117_readd_column_after_drop_conversion covers the ILLEGAL_COLUMN shape (UInt64 dropped, UInt32 re-added). The Nullable to non-Nullable shape above raises LOGICAL_ERROR instead and aborts a debug server, which is why the fuzzer is the one finding it.

On BuzzHouse 1218-27e6: 4 occurrences in CIDB in the last 30 days, all in BuzzHouse jobs on PRs, none on master, and no fixing PR exists for it.

alexey-milovidov and others added 2 commits October 2, 2026 12:54
…pending-rename-117323

Master removed the `MutationsSnapshot`-based overload of `getColumnDefaultnessStatsUnavailableReason`;
the conflict is resolved by taking the master side, the `num_metadata` check of this PR remains in the
counter-based overload.
…LUMN` with rename or re-add

Add a regression for the `getColumnsWithStaleIndexes` guard in `collectTextIndexReadInfos`: with a
pending `DROP INDEX`, `DROP COLUMN`, `RENAME COLUMN` (or same-name `ADD COLUMN`), `ADD INDEX`, the
text index file of the old part describes the dropped column. Each direct read is compared against a
row-scan control. Without the guard the test returns the matches of the dropped data.

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

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. That matches what I saw: the assumeNotNull LOGICAL_ERROR comes from the pending-drop conversion, which is tracked by #116416 and fixed by #118585, so nothing in this PR needs to change for it. I merged the latest master here to resolve a conflict in MergeTreeData.cpp and added the text-index regression the AI review asked for.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The AST fuzzer (amd_debug, targeted, old_compatibility) failure on 29947cf (Bad cast from type DB::ColumnDecimal<DB::Time64> to DB::ColumnLowCardinality in performRequiredConversions, report) has the same cause as the earlier one: a pending-drop column conversion. The fuzzer ran ALTER TABLE t DROP COLUMN x, ADD COLUMN x Time64(4) while x LowCardinality(Int64) was still on disk. I reproduced it with the official 26.7 release, so this PR does not cause it:

CREATE TABLE t (id Int64, x LowCardinality(Int64)) ENGINE = MergeTree ORDER BY tuple();
SYSTEM STOP MERGES t;
INSERT INTO t VALUES (1, 1), (2, 2);
ALTER TABLE t DROP COLUMN x, ADD COLUMN x Time64(4) SETTINGS alter_sync = 0, mutations_sync = 0;
SELECT groupArrayDistinct(x) FROM t; -- Bad cast

Tracked by #116416 and fixed by #118585. I merged the latest master, and the four tests of this PR pass locally.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI on 999bbc8:

I merged the latest master. The four tests of this PR pass locally on the merged build.

alexey-milovidov and others added 2 commits October 6, 2026 12:24
…ation touches other columns

`filterPartsByStatistics` disabled statistics pruning for any part with a pending
`RENAME COLUMN` or `DROP COLUMN`. Narrow it to the parts where a renamed (old or new
name) or dropped column overlaps one of the columns whose estimates the pruner may
consult, using the same dotted-name overlap logic as `canUseIndex`. The set of such
columns comes from the new `StatisticsPartPruner::getColumnsConsultedByEstimates`,
because `getUsedColumns` is only filled while parts are checked.

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

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (69781c8f). The merge was clean, clickhouse builds, and all 12 tests of this PR pass locally. The only red job on 86a35c13 was Upgrade check (amd_release), failing with the UNKNOWN_IDENTIFIER mutation retries from 04653 (#120975). Its fix, #125293, is still not merged. The upgrade check takes its tests from the previous stable tag, so that job may stay red until the fix is merged and backported. There are no unresolved review threads.

alexey-milovidov and others added 4 commits November 6, 2026 10:03
…defaultness stats

`getColumnDefaultnessStats` accepted any still-active captured part when the storage did not
track removed mutation versions, which is the case for `StorageReplicatedMergeTree`. A
`KILL MUTATION` (`ReplicatedMergeTreeQueue::removeMutation`) or the cleanup of a mutation from
ZooKeeper (`updateMutations`) between capturing the parts and taking the mutations snapshot
removed the commands while the part was still active, so the rewrite used the dropped column's
`num_defaults`.

`ReplicatedMergeTreeQueue` now records the maximum removed mutation block number per partition
(block numbers of replicated mutations are per partition), and `getMaxRemovedMutationVersion`
takes the partition id. The check is done for every captured part, as for `StorageMergeTree`.

New test `05507_trivial_count_sparsity_replicated_mutation_killed_after_parts_snapshot` follows
the reviewer's interleaving.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`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]>
…eeQueue::clear`

After a reconnect to ZooKeeper the queue is reinitialized: `clear` discards
the local mutation history, and it is loaded again only later. A part captured
by a running query may still need the commands of these mutations, so the
maximum removed mutation block number is advanced for each partition, and
`getColumnDefaultnessStats` declines the trivial count rewrite for such parts.

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

In `ReplicatedMergeTreeQueue::clear`, `updateMaxRemovedMutationBlockNumber` may throw
(allocation in `unordered_map::operator[]`) after `mutations_by_znode` was already
cleared, leaving `mutations_by_partition` with dangling pointers. Update the watermarks
first, then clear the index before its owning map. In `updateMutations` and
`removeMutation` the watermarks are now recorded before the partition index is erased,
so a mutation never disappears without a watermark.

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

Copy link
Copy Markdown
Member Author

🕵 The only red check on 33a3ae8e was CH Inc sync ("Failed. Needs manual intervention"): the sync PR conflicted with private master in files this PR no longer touches (AlterConversions.h, IndexReadRangesRefiner.cpp, MergeTreeDataSelectExecutor.cpp, ...). I overlaid the current 25 PR files onto private master (16 plain takes and 9 clean 3-way merges, and the numstat matches this PR's diff exactly), then pushed it to the sync branch. The sync PR is MERGEABLE now and private CI is running. All other checks are green, and there are no unresolved review threads.

alexey-milovidov and others added 2 commits November 11, 2026 11:42
`05507_trivial_count_sparsity_replicated_mutation_killed_after_parts_snapshot`
and `05508_trivial_count_sparsity_replicated_mutations_cleared_by_reconnect`
exercise the mutation bookkeeping of `ReplicatedMergeTreeQueue` (`KILL MUTATION`
and the queue reinitialization after a ZooKeeper reconnect). In the private CI
the `ReplicatedMergeTree` engine is replaced with `SharedMergeTree`, which does
not use `ReplicatedMergeTreeQueue`, so the tests failed there with
"result differs with reference" in all stateless jobs of the `CH Inc sync` PR.

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

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (clean merge; the changed translation units compile) and pushed e99fe412. The only red check on 33a3ae8e was CH Inc sync ("tests failed"): 05507_trivial_count_sparsity_replicated_mutation_killed_after_parts_snapshot and 05508_trivial_count_sparsity_replicated_mutations_cleared_by_reconnect failed in every private stateless job. Private CI replaces ReplicatedMergeTree with SharedMergeTree, which does not use the ReplicatedMergeTreeQueue mutation bookkeeping these two tests exercise, so both are now tagged no-shared-merge-tree. Whether SharedMergeTree needs a similar fix should be checked separately in the private repository.

alexey-milovidov and others added 2 commits November 12, 2026 15:37
The style check now requires an `event_time` condition in queries to `system.text_log`.

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

Copy link
Copy Markdown
Member Author

🕵 The red Style check on e99fe412 came from a new rule on master: queries to system.text_log must have an event_time condition. Added event_time >= now() - INTERVAL 1 HOUR to the five affected tests (05407, 05408, 05448, 05507, 05508). Bugfix validation and Finish Workflow were red only because they were dropped after the style check. Also merged the latest master (clean merge; the changed translation units compile) and pushed 5756591c.

alexey-milovidov and others added 2 commits November 14, 2026 07:20
`MergeTreeData::getColumnDefaultnessStats` captured its own parts and took a fresh
mutations snapshot. A mutation could be removed from the history between the query's
analysis and that point (`KILL MUTATION`, `finished_mutations_to_keep`, reinitialization
of the replication queue), and the watermarks of removed mutation versions added for
that did not cover every case: a replicated part inserted while the schema update is
queued has a newer data version but an older metadata version than the removed
`DROP COLUMN`, so its on-the-fly commands are selected by the metadata version.

Take the parts and the mutations from the storage snapshot of the table expression
instead: exactly what the row scan of the same query reads. A mutation that finishes
or is removed later does not change what the query reads, so it cannot change the
stats either. This makes the removed-version tracking in `StorageMergeTree` and
`ReplicatedMergeTreeQueue` unnecessary, so it is removed.

Also fix the flaky `05507_trivial_count_sparsity_replicated_mutation_killed_after_parts_snapshot`
(and the same race in `05508`): with `alter_sync = 0` the replica may not have applied
the new metadata yet when the query runs, so both counts were `0`. Wait until reads
apply the pending `DROP COLUMN x, ADD COLUMN x Int64`.
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117814&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_binary%2C%20flaky%20check)
#117814

New test `05768_trivial_count_sparsity_replicated_insert_before_metadata_killed` covers
the reviewer's interleaving with an insert while the schema update is queued.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The live check of patch parts in `getColumnDefaultnessStatsUnavailableReason` is not
enough since the stats are taken from the query's storage snapshot: a lightweight
`UPDATE` can be materialized and its patch part removed by `clearUnusedPatchParts`
after the snapshot is captured, while the reads of the captured base parts still apply
the captured patch. Reject snapshots with patch parts or on-the-fly data/alter mutations.

The failpoint `mt_column_defaultness_stats_pause_after_parts_snapshot` is moved before
the live checks so that a test can change the live state after the snapshot is taken.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 18, 2026
alexey-milovidov and others added 2 commits November 21, 2026 09:19
The check added in the previous commit rejected the defaultness stats whenever the
mutations snapshot of the query had any data or alter mutation. But the snapshot lists
every mutation of the table that passes the `need_*_mutations` filter, including the
finished ones kept in the history (`finished_mutations_to_keep`), which are already
applied to all parts. So after any finished `MODIFY COLUMN` (a `READ_COLUMN` command)
`optimize_trivial_count_with_sparsity_filter` was never used again, which failed
`05237_trivial_count_sparsity_filter_stats_after_alter` in the fast test.

Check instead, for each part of the snapshot, whether it has patch parts
(`getPatchesForPart`) or data/alter mutation commands to apply on the fly
(`getOnFlyMutationCommandsForPart`). These are exactly what the reads of that part apply.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117814&sha=63958992fc1dfd57da88b797a9163e69e96be677&name_0=PR&name_1=Fast%20test
PR: #117814

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The red Fast test on 63958992 was a real regression from the previous commit: 05237_trivial_count_sparsity_filter_stats_after_alter stopped being served by the rewrite. The check of the snapshot's patch parts and on-the-fly mutations was global, but the mutations snapshot also lists finished mutations kept in the history, so after any finished MODIFY COLUMN the rewrite was never used again. The check is now per part (getPatchesForPart, getOnFlyMutationCommandsForPart), which is exactly what the reads of that part apply. Bugfix validation and Finish Workflow were red only because they were dropped after the fast test, and the stateless jobs of CH Inc sync failed on the same test.

Also merged the latest master (clean merge) and pushed e14fd425559f. clickhouse builds, and 05237 plus all tests of this PR (including the replicated, transaction and patch-part ones) pass locally. There are no unresolved review threads.

@stresshouse

stresshouse Bot commented Nov 21, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

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

no significant changes detected. K_source=4 K_base=23 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 9fca020a-1ac1-47fe-80f6-ee2e0eb9a0c2
  • MIRAI run: aa31f246-1940-48e5-923a-e7fed9d6a5e8
  • PR check IDs:
    • clickbench_641454_1795259554
    • clickbench_641467_1795259554
    • tpch_adapted_1_official_641476_1795259555
    • tpch_adapted_1_official_641518_1795259554

alexey-milovidov and others added 3 commits November 24, 2026 09:38
… in the defaultness stats

The storage snapshot of a query is taken before the parts are filtered for reading. A query that is
a part of a lightweight update reads only the parts up to the block numbers allocated by the update
(`Context::getPartitionIdToMaxBlock`, applied in `MergeTreeDataSelectExecutor::selectPartsToRead`),
but `filterPartsForColumnDefaultnessStats` ignored that cutoff, so the trivial `count()` rewrite of
`optimize_trivial_count_with_sparsity_filter` counted the defaults of a part inserted after the update
allocated its block number, and the update persisted a count that its own row scan would not produce.

The cutoff is now applied in `MergeTreeData::filterPartsForColumnDefaultnessStats`, and
`StorageReplicatedMergeTree` applies it together with the quorum boundary of `select_sequential_consistency`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…rsity_replicated_insert_before_metadata_killed`

The flaky check failed with `No part all_0_0_0 in committed state` in `ALTER TABLE ... DROP PART 'all_0_0_0'`:
an insert into `ReplicatedMergeTree` that is retried (e.g. after an injected Keeper fault) allocates another
block number, so the seed part is not always `all_0_0_0`. The rest of the multi-query script was then skipped,
which produced the other errors of the run. The test now takes the name of the part from `system.parts`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117814&sha=e14fd425559f7fc426062c68bf3402d528c4bf02&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20flaky%20check%29
#117814

Co-Authored-By: Claude Fable 5.2 <[email protected]>
query_context->getSettingsRef()[Setting::select_sequential_consistency]);
/// The block numbers allocated by a lightweight update are a cutoff independent of the quorum,
/// so both filters are applied, the same as in `readLocalSequentialConsistencyImpl`.
parts = MergeTreeData::filterPartsForColumnDefaultnessStats(std::move(parts), query_context);

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.

[Blocker] Use the same combined cutoff as replicated row reads.

With select_sequential_consistency = 1, readLocalSequentialConsistencyImpl (lines 6490–6499) starts with getMaxAddedBlocks and clamps only the partitions present in the update's map; partitions absent from that map remain readable. Calling the base filter here first instead erases those partitions. The statistics and the row scan therefore still count different row sets.

This needs no concurrent insert: create a partitioned ReplicatedMergeTree with exact defaultness statistics and one x = 0 row in each of partitions 1 and 2, then execute:

UPDATE t SET y = (SELECT count() FROM t WHERE x = 0)
IN PARTITION 1 WHERE p = 1
SETTINGS enable_lightweight_update = 1,
    select_sequential_consistency = 1,
    optimize_trivial_count_query = 1,
    optimize_trivial_count_with_sparsity_filter = 1;

The explicit partition scope makes allocateBlockNumbersInAffectedPartitions put only partition 1 in the update map. By the current code, the rewrite counts one row and stores y = 1, whereas disabling it lets the scalar subquery scan both partitions and store y = 2.

Please share the combined-cutoff construction with readLocalSequentialConsistencyImpl, or decline the rewrite for this combination, and add a two-partition replicated regression comparing the optimization enabled and disabled. The new 05872 exercises only plain MergeTree.

This branch has not been deployed

No deployments
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Statistics-based part pruning uses a pending-renamed column's stale statistics — silent missing rows at default settings

3 participants