Repository navigation
Do not prune a part by statistics while a RENAME COLUMN is pending - #117814
alexey-milovidov wants to merge 57 commits into
Conversation
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
|
Workflow [PR], commit [64d5f8a] Summary: ❌
AI ReviewSummaryThe 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 Findings❌ Blockers
Tests
Missing context / blind spots
Final VerdictStatus: ❌ Block Make replicated statistics and row reads use identical partition cutoffs and add the focused regression. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes222 object files changed (+56.58 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units728 translation units recompiled, 4709 s compile time in total, 728 of them have a recent master baseline. |
…pending-rename-117323
`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]>
…pending-rename-117323
…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]>
…pending-rename-117323
…` 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]>
|
🕵 @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 ( 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 |
|
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.
#118585 puts It still reproduces on master ( 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 Your repro as posted returns One gap in #118585 as it stands: On BuzzHouse 1218-27e6: 4 occurrences in CIDB in the last 30 days, all in |
…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]>
|
🕵 Thanks @groeneai. That matches what I saw: the |
|
🕵 The 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 castTracked by #116416 and fixed by #118585. I merged the latest |
|
🕵 CI on 999bbc8:
I merged the latest |
…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]>
|
🕵 Merged the latest |
…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]>
|
🕵 The only red check on |
`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]>
|
🕵 Merged the latest |
The style check now requires an `event_time` condition in queries to `system.text_log`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The red |
`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]>
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]>
|
🕵 The red Also merged the latest |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
… 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); |
There was a problem hiding this comment.
[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.
While a
RENAME COLUMNis still a pending on-the-fly mutation, or a pendingDROP COLUMN xis followed by adding a column namedxagain, reads apply the metadata mutation, but the per-columnnum_defaultsinserialization.jsonstay keyed by the names the columns have on disk. The trivialcount()rewrite ofoptimize_trivial_count_with_sparsity_filteranswersSELECT count() FROM t WHERE x = 0from those counters, so it could count another column's defaults, or the defaults of the dropped data instead of the re-added column.MergeTreeData::getColumnDefaultnessStatsnow 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 pendingDROP COLUMNorRENAME COLUMNin 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 anUPDATEno 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
masterby #119337. This branch's own changes for those paths, and their tests, were dropped in favour of it when mergingmaster.Closes: #117323
Related: #119337
Changelog category (leave one):
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 aRENAME COLUMNorDROP COLUMN+ADD COLUMNofxis 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]