Repository navigation
Build only the statistics a mutation is supposed to recompute - #112009
Conversation
`MutateSomePartColumnsTask` loads every statistics object from the source part, and `PartMergerWriter` then rebuilt every loaded object that happened to appear in the block it was writing. There was no selection step, so a statistics object that had only been loaded in order to be carried over unchanged was rebuilt against whatever block the mutation produced. When metadata had moved ahead of the part without rewriting it - a metadata-only conversion from the `allowed_conversions` table (Enum8 to Int8, DateTime to UInt32, Date to UInt16 and back) updates `column.statistics.data_type` while leaving the part and its statistics file at the old type - the block column arrived at the new type and the type check added in ClickHouse#106963 threw Type mismatch when building statistics for column 'e': statistics expect type Enum8('a' = 1, 'b' = 2) but block has type Int8 which aborts debug and sanitizer builds. The mutation then retried forever, which is why the stress runs also reported `Cannot start clickhouse-server` and hung checks. `MergeTask` never had this bug because it selects explicitly through `statistics_to_build_by_part` and its `BuildStatisticsTransform`. This adds the same distinction to the mutation writer: a separate `statistics_to_build` set holds the objects to compute (all of them on the all-columns path, where they were just created empty from current metadata; only the ones `processStatisticsChanges` replaced with fresh empty objects on the some-columns path), while everything else is loaded, preserved and re-serialized untouched. The set is deliberately not derived from `updated_header`: that header is empty by design for `MATERIALIZE STATISTICS` and for index and projection materializations, so gating on it would serialize empty statistics. Second half, in `MutationsInterpreter::prepare`: a column a mutation does rewrite must have its statistics recomputed, and `updated_columns` / `changed_columns` missed three emitters - `MATERIALIZE COLUMN`, `UPDATE`'s dependent MATERIALIZED columns via `affected_materialized`, and the MATERIALIZED recalculation `CLEAR COLUMN` triggers. Rather than adding a third and fourth per-command insert, the names are now collected from the non-readonly stages themselves, which is exactly the set written into the new part. Cleared columns are excluded because the mutation drops their statistics and re-registering them would recreate an object for a column the part does not contain. Both `MutatePlainMergeTreeTask` and `MutateFromLogEntryTask` reach this code through the single `MutateTask`, so MergeTree, ReplicatedMergeTree and SharedMergeTree are covered by the same change.
Internal second-model review (2 findings: 0 fixed, 2 disagreed with evidence)Before opening this PR I ran an independent cold review of the resulting code plus a
|
Pre-PR validation gate
Each half of the fix, and each of the two guards protecting the paths this change could break, was 50 randomized runs of the new test pass. A 152-test statistics-focused regression sweep produces the |
|
cc @alesapin @scanhex12 — could you review this? |
|
Workflow [PR], commit [7f642bc] Summary: ✅
AI ReviewSummaryThis PR fixes the mutation-side statistics selection bug and the new stateless coverage is well targeted, but I do not consider it ready yet because one previously reported correctness gap remains open in the same stage-emitted rewrite paths. Statistics are now recomputed for those writes, but skip indexes and projections can still be hardlinked stale. Findings❌ Blockers
Final VerdictChanges required: the existing stale skip-index / projection path is still present in the current code, so the mutation correctness hole is not fully closed yet. |
| /// Every column emitted by a non-readonly stage is written into the new part at its current | ||
| /// metadata type, so its statistics have to be recomputed rather than carried over from the | ||
| /// source part. `updated_columns` and `changed_columns` do not cover all emitters: MATERIALIZE | ||
| /// COLUMN, UPDATE's dependent MATERIALIZED columns and the MATERIALIZED recalculation caused | ||
| /// by CLEAR COLUMN all write a column without registering it there. Collect the names from | ||
| /// the stages themselves so that a newly added emitter cannot be missed here. | ||
| NameSet columns_written_by_stages; | ||
| for (const auto & stage : stages) | ||
| { | ||
| if (stage.is_readonly) | ||
| continue; | ||
|
|
||
| for (const auto & [column_name, _] : stage.column_to_updated) | ||
| columns_written_by_stages.insert(column_name); | ||
| } | ||
|
|
||
| for (const auto & column : metadata_snapshot->getColumns()) | ||
| { | ||
| if (column.statistics.empty()) | ||
| continue; | ||
|
|
||
| /// A cleared column is excluded from the new part and its statistics are removed by the | ||
| /// mutation. Registering it would recreate an empty statistics object for a column that | ||
| /// the new part does not contain. | ||
| bool written_by_stage = columns_written_by_stages.contains(column.name) | ||
| && !cleared_columns_with_dependencies.contains(column.name); | ||
|
|
||
| if (updated_columns.contains(column.name) || changed_columns.contains(column.name) | ||
| || patch_updated_columns.contains(column.name)) | ||
| || patch_updated_columns.contains(column.name) || written_by_stage) |
There was a problem hiding this comment.
This closes the statistics half of the "stage-emitted columns were never registered" gap, but the same emitters are still invisible to the skip-index / projection rebuild gates a few lines above (materialized_indices at 1551-1575, materialized_projections at 1592-1609). A concrete trace is:
UPDATE src = ...wheremis a dependentMATERIALIZEDcolumn, orMATERIALIZE COLUMN m.- The mutation adds a non-readonly stage that rewrites
m, so this newcolumns_written_by_stagesblock correctly rebuildsm's statistics. updated_columns,changed_columns, andpatch_updated_columnsstill do not containm, so an index / projection defined onmis hardlinked from the source part instead of being rebuilt.
Once the rewritten values move outside the old index / projection contents, queries can read stale projection rows or prune away matching granules. The fix needs to drive materialized_indices / materialized_projections from the same stage-written column set (or otherwise union those columns into the existing changed checks), not just materialized_statistics.
There was a problem hiding this comment.
I checked the trace and it is real, but it is not a regression of this PR, and the part of it that
this PR could plausibly own is already covered elsewhere. Measurements below, all on debug builds:
a pristine master snapshot (26.8.1.1) and this PR's head 0ff719aa5bf5.
1. Every shape you describe behaves identically on master and on this branch.
Skip index over a MATERIALIZED column, driven by ALTER TABLE ... UPDATE src (your exact trace):
CREATE TABLE t_idx (k UInt64, src UInt64, m UInt64 MATERIALIZED src * 10,
INDEX idx_m m TYPE minmax GRANULARITY 1)
ENGINE = MergeTree ORDER BY k SETTINGS index_granularity = 1, min_bytes_for_wide_part = 0;
INSERT INTO t_idx (k, src) VALUES (1, 1), (2, 2), (3, 3);
ALTER TABLE t_idx UPDATE src = 100 WHERE k = 1 SETTINGS mutations_sync = 2;
SELECT count() FROM t_idx WHERE m = 1000; -- 0 (wrong)
SELECT count() FROM t_idx WHERE m = 1000 SETTINGS use_skip_indexes = 0; -- 1 (ground truth)| Shape | master | this branch |
|---|---|---|
skip index over m, UPDATE src |
0 vs 1 |
0 vs 1 |
MODIFY COLUMN m MATERIALIZED ... + MATERIALIZE COLUMN m, skip index |
0 vs 1 |
0 vs 1 |
projection over m, UPDATE src |
stale {10,20,30} |
stale {10,20,30} |
2. This PR does not touch either gate, and structurally cannot widen what a mutation writes.
The index gate and the projection gate are byte-identical to master in this diff (I hashed both
regions at origin/master and at HEAD: index 40f09119940128..., projection 04576019..., equal
in both cases). And git diff <merge-base> HEAD -- src/ contains zero added lines matching
stages.emplace_back|column_to_updated.emplace|addStageIfNeeded, so the diff cannot add a column to
the written set. It only changes which of the already-written columns have their statistics
recomputed instead of carried over from the source part at a stale type.
3. The UPDATE-driven half of your trace is already fixed by #110648.
That PR builds an all_affected_materialized union and ORs it into exactly these two gate
predicates. I emulated that union here, rebuilt, and re-measured: the skip-index case goes 0 to
1 and the projection case goes {10,20,30} to {20,30,1000}. Both fixed. So the shape you wrote
up (step 1 UPDATE src = ... with a dependent MATERIALIZED m) has an owner already.
4. What genuinely is not covered is the MATERIALIZE COLUMN variant, and I have split it out.
With the #110648 union emulated, the MATERIALIZE COLUMN case still returns 0. The reason is
structural: column_to_affected_materialized is written only at MutationsInterpreter.cpp:800,
keyed on updated_columns, and updated_columns is populated only from alter->update_assignments
(:734-748). A bare MATERIALIZE COLUMN carries no update assignments, so it enters neither set.
The only closure that sees it is the stage-derived one this PR introduces for statistics.
I have filed that residual as its own item with the reproducer above rather than bundling it here,
because it is a separate root cause with its own risk surface. Concretely, driving the index and
projection gates off a stage-derived set needs validating on two paths where that set is empty by
design: ALTER TABLE ... MATERIALIZE STATISTICS (whose getUpdatedHeader() deliberately returns an
empty block for MUTATE_INDEX_STATISTICS_PROJECTION) and a plain DELETE on
MutateAllPartColumnsTask. A gate driven off the wrong set there would silently write empty
artifacts, which is worse than the bug. That verification does not belong on a statistics fix.
So: no change here, and the index and projection half is tracked with a fix task and a reproducer.
There was a problem hiding this comment.
Follow-up to my note above, where I said the index and projection half was tracked separately: it is already fixed by an open PR, so no separate fix is owed from me.
#99647 (@ Onyx2406, open) covers exactly this. It collects MATERIALIZE_COLUMN targets in the initial command scan, feeds them into column_to_affected_materialized, and then registers the affected skip indices / projections / statistics together with their required columns as dependencies inside the MATERIALIZE_COLUMN branch itself.
Measured on its prebuilt debug binary (dac94a4bc8f05d805edd769769428c5c0d368143, 26.7.1.1) against the master debug snapshot (26.8.1.1), Full Wide parts, all defaults otherwise:
| Shape | master | #99647 | ground truth |
|---|---|---|---|
minmax index over m, MODIFY COLUMN m MATERIALIZED ... + MATERIALIZE COLUMN m |
0 |
1 |
1 |
minmax index over (a + m) (multi-column) |
0 |
1 |
1 |
projection over m |
[10,20,30] |
[1000,2000,3000] |
[1000,2000,3000] |
bare MATERIALIZE COLUMN on a never-materialized column |
1 |
1 |
1 |
Compact part (index rebuilt via the !is_full_wide_part path) |
1 |
1 |
1 |
Zero residual scope: every variant that is wrong on master is fixed there, and the two that are already correct on master stay correct.
Worth noting that #99647 is the better layer than what I had planned. I was going to OR a stage-derived columns_written_by_stages set into the two gate predicates, which selects the artifact for rebuild but does not put the artifact's other required columns into the mutation pipeline. For a multi-column index like INDEX idx_sum (a + m) that is not enough, and for a projection MutateTask::calculateProjection substitutes a type-default for the missing column (MutateTask.cpp:1918-1939), which would have produced silently incorrect projection data rather than stale data. #99647 registers the dependencies, so the rebuild reads real values. It also handles a residual I had wrongly written off: the MATERIALIZE COLUMN guard only checks getSortingKeyColumns (result names), so a column feeding a partition-key or sorting-key expression was accepted and then rewritten while MutateTask preserves the source partition metadata and, on the some-columns path, the source minmax index; #99647 refuses those cases explicitly.
Master is still unfixed (git merge-base --is-ancestor refs/pull/99647/head origin/master is false, and none of its new symbols are present), so the defect is live until that PR lands. I am tracking it there rather than opening a competing PR.
Session id: cron:clickhouse-plan-slot-1:20260727-090001
CI finish ledger — 0ff719aEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Not PR-caused: this PR's diff touches Session id: cron:our-pr-ci-monitor:20260727-120000 |
|
Fixing PR for the The |
…tistics-selection
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 34/34 (100.00%) · Uncovered code |
CI finish ledger — 7f642bcEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
CI is fully finished on this commit with zero failing checks. Session id: cron:our-pr-ci-monitor:20260729-043000 |
|
@hanfei1991 this seems good to me, can you give a final look? Shouldn't take long |
|
@alexey-milovidov could you apply Two Stress aborts 38 minutes apart today, same
26.7 is the useful arm: it already has #106963 and still aborts. #106963 only replaces the opaque The 26.7 column CIDB over 45 days: both signatures are extinct on master after this merged (last master hits 2026-07-04 and 2026-07-07) and appear only where it is missing.
Port simulation against today's tips, base pinned at this PR's merge parent:
Symbol counts in the simulated 26.6 and 26.7 trees match master ( |
…election Build only the statistics a mutation is supposed to recompute
Backport #112009 to 26.7: Build only the statistics a mutation is supposed to recompute
Closes: #111202
Related: #106963 (added the diagnostic that this removes the cause of), #109415 (my earlier attempt, closed unmerged)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
LOGICAL_ERROR(Type mismatch when building statistics for column) during aMergeTreemutation of a table whose column type was changed by a metadata-onlyALTER MODIFY COLUMN(for exampleEnum8toInt8orDateTimetoUInt32) while the column carries statistics. The mutation now recomputes only the statistics of columns it actually rewrites and carries the rest over unchanged, and a column rewritten byMATERIALIZE COLUMN, by anUPDATEof a column aMATERIALIZEDcolumn depends on, or byCLEAR COLUMNnow gets its statistics recomputed instead of keeping stale content.Description
Runnable reproducer on master, single session, no fuzzer and no concurrency:
That is frame-for-frame the stack the stress tests report in #111202. It is an exception, so release
builds handle it; debug and sanitizer builds abort, the mutation retries forever, and the stress run
then also reports
Cannot start clickhouse-serverand a hung check.Cause.
MutateSomePartColumnsTaskloads every statistics object from the source part, andPartMergerWriterrebuilt every loaded object that happened to appear in the block it was writing.There was no selection step, so an object loaded only in order to be carried over unchanged was
rebuilt against whatever block the mutation produced. A conversion from the
allowed_conversionstable in
isMetadataOnlyConversion(Enum8/Enum16toInt8/Int16,DateTimeandUInt32,DateandUInt16) schedules no mutation at all, yet still updatescolumn.statistics.data_typewhile leaving the part and its statistics file at the old type. The stale object loads cleanly
because the V4 deserialize guard is keyed on the part's own type, so old-vs-old passes.
MergeTasknever had this bug: it selects explicitly throughstatistics_to_build_by_partand itsBuildStatisticsTransform. This PR gives the mutation writer the same distinction, through aseparate
statistics_to_buildset that holds the objects to compute while everything else isloaded, preserved and re-serialized untouched. The set is populated per path and deliberately not
derived from
updated_header: that header is empty by design forMATERIALIZE STATISTICSand forindex and projection materializations, so gating on it would serialize empty statistics.
Second half. A column the mutation does rewrite must have its statistics recomputed, and
updated_columns/changed_columnsmissed three emitters:MATERIALIZE COLUMN,UPDATE'sdependent
MATERIALIZEDcolumns, and theMATERIALIZEDrecalculationCLEAR COLUMNtriggers. Eachwrites the column at its current type without registering it, which is also why every plain
MODIFY COLUMNreproduction self-heals (READ_COLUMNdoes register it). Rather than adding a thirdand fourth per-command insert, the names are collected from the non-readonly stages themselves,
which is exactly the set written into the new part. Cleared columns are excluded because the
mutation drops their statistics and re-registering them would recreate an object for a column the
part does not contain.
Both
MutatePlainMergeTreeTaskandMutateFromLogEntryTaskreach this through the singleMutateTask, so MergeTree, ReplicatedMergeTree and SharedMergeTree are covered by the same change.Two notes on the earlier attempt: my
reconcileWithColumnsPR #109415 was closed unmerged, and itsNullablebased theory was simply wrong (that path emitsREAD_COLUMNand self-heals). This is adifferent, demonstrated mechanism, and the fix mirrors selection logic that already exists in
MergeTaskrather than adding a new one.The new test covers all four affected mutation kinds plus the two paths this change could otherwise
have broken (
MATERIALIZE STATISTICSandDELETEmust still leave non-empty, usable statistics),and it asserts the recomputed content through
system.parts_columnsestimates so that stalestatistics content is caught, not just the absence of the abort. CI report for the failure being
fixed: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=e889e335e3a4e27471a1830c7232d09164e58345&name_0=MasterCI&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29
Version info
26.7.7.93