Skip to content

Build only the statistics a mutation is supposed to recompute - #112009

Merged
hanfei1991 merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-mutate-task-statistics-selection
Jul 29, 2026
Merged

hanfei1991 merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-mutate-task-statistics-selection

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111202
Related: #106963 (added the diagnostic that this removes the cause of), #109415 (my earlier attempt, closed unmerged)

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

Fixed a LOGICAL_ERROR (Type mismatch when building statistics for column) during a MergeTree mutation of a table whose column type was changed by a metadata-only ALTER MODIFY COLUMN (for example Enum8 to Int8 or DateTime to UInt32) 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 by MATERIALIZE COLUMN, by an UPDATE of a column a MATERIALIZED column depends on, or by CLEAR COLUMN now gets its statistics recomputed instead of keeping stale content.

Description

Runnable reproducer on master, single session, no fuzzer and no concurrency:

SET mutations_sync = 2;
SET materialize_statistics_on_insert = 1;

CREATE TABLE tab (id Int64, e Enum8('a' = 1, 'b' = 2) MATERIALIZED 'a' STATISTICS(uniq, basic))
ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 1;

INSERT INTO tab (id) VALUES (1), (2);
ALTER TABLE tab MODIFY COLUMN e Int8 MATERIALIZED 2;   -- metadata-only, schedules no mutation
ALTER TABLE tab MATERIALIZE COLUMN e;                  -- aborts
Logical error: 'Type mismatch when building statistics for column 'e':
               statistics expect type Enum8('a' = 1, 'b' = 2) but block has type Int8'
Statistics.cpp:619  checkColumnTypeMatchesStatistics
Statistics.cpp:644  ColumnsStatistics::buildIfExists
MutateTask.cpp:1832 PartMergerWriter::mutateOriginalPartAndPrepareProjections
MutateTask.cpp:2484 MutateSomePartColumnsTask::executeStep

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-server and a hung check.

Cause. MutateSomePartColumnsTask loads every statistics object from the source part, and
PartMergerWriter rebuilt 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_conversions
table in isMetadataOnlyConversion (Enum8/Enum16 to Int8/Int16, DateTime and UInt32,
Date and UInt16) schedules no mutation at all, yet still updates column.statistics.data_type
while 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.

MergeTask never had this bug: it selects explicitly through statistics_to_build_by_part and its
BuildStatisticsTransform. This PR gives the mutation writer the same distinction, through a
separate statistics_to_build set that holds the objects to compute while everything else is
loaded, preserved and re-serialized untouched. The set is populated per path and 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. A column the mutation does rewrite must have its statistics recomputed, and
updated_columns / changed_columns missed three emitters: MATERIALIZE COLUMN, UPDATE's
dependent MATERIALIZED columns, and the MATERIALIZED recalculation CLEAR COLUMN triggers. Each
writes the column at its current type without registering it, which is also why every plain
MODIFY COLUMN reproduction self-heals (READ_COLUMN does register it). Rather than adding a third
and 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 MutatePlainMergeTreeTask and MutateFromLogEntryTask reach this through the single
MutateTask, so MergeTree, ReplicatedMergeTree and SharedMergeTree are covered by the same change.

Two notes on the earlier attempt: my reconcileWithColumns PR #109415 was closed unmerged, and its
Nullable based theory was simply wrong (that path emits READ_COLUMN and self-heals). This is a
different, demonstrated mechanism, and the fix mirrors selection logic that already exists in
MergeTask rather 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 STATISTICS and DELETE must still leave non-empty, usable statistics),
and it asserts the recomputed content through system.parts_columns estimates so that stale
statistics 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

  • Backported to: 26.7.7.93

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

Copy link
Copy Markdown
Collaborator Author
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
second-model review pass. Seven items were raised in total; five were closed during my own
review by code reading or by the recorded evidence, and two substantive findings are answered
below. Nothing was left unaddressed.

⚠️ Orphan statistics entry for a cleared column on the lightweight-update patch route (disagreed, but real on master)

Claim: clearing a column that a lightweight-update patch also touches registers its statistics
for recomputation, so processStatisticsChanges removes the entry for DROP_COLUMN and
immediately re-adds it from stats_to_recalc, leaving statistics_<col>.stats in
statistics.packed for a column the part does not contain.

The observation looks correct, but it is not caused by this PR and it is not what this PR
changes. The registration comes from the || patch_updated_columns.contains(column.name)
disjunct, which is byte-identical on master:

git show origin/master:src/Interpreters/MutationsInterpreter.cpp | sed -n '1612,1620p'

The only edit this PR makes to that statement is appending || written_by_stage, and
written_by_stage is the one disjunct that carries the cleared-column exclusion. The
read_for_patch -> patch_updated_columns insert the finding cites is likewise untouched. So
the necessary step of the scenario - registering a cleared column - is performed entirely by
pre-existing code, and the scenario reproduces the same way without this PR.

In the direction this PR does own, the change strictly reduces orphan risk: removing the new
!cleared_columns_with_dependencies.contains(...) guard makes the mutated part carry
statistics_m1.stats for a column absent from system.parts_columns, and with the guard the
entry is correctly absent (verified by a mutation build).

I am not folding the patch-route fix in here. It would need a new set covering every cleared
column, not just those with dependents, so it changes behaviour on a path this PR does not
touch, and I have no reproduction of user-visible harm from it on master yet. That is a
separate change with its own test.

💡 Blanket no-random-merge-tree-settings tag instead of pinning one setting (disagreed)

Claim: drop the tag and pin min_bytes_for_full_part_storage = 0 instead, so unrelated
randomized coverage stays enabled.

That swap would make the test flaky. Removing the tag re-enables all 61 randomized MergeTree
settings, two of which move the values this test asserts:

  • auto_statistics_types (tests/clickhouse-test:1732, generator at :1312-1320) is applied
    by addImplicitStatistics (src/Storages/Statistics/Statistics.cpp:864-891) to every
    non-ALIAS/non-EPHEMERAL column, so columns expected to carry no statistics acquire them.
  • ratio_of_defaults_for_sparse_serialization (:1675-1677) switches columns to Sparse, and
    StatisticsUniq::build then counts the sparse values column plus a possible extra default -
    its own comment says so (src/Storages/Statistics/StatisticsUniq.cpp:33-38). The test asserts
    exact estimates.cardinality.

The premise is also inverted: min_bytes_for_full_part_storage defaults to 0
(src/Storages/MergeTree/MergeTreeSettings.cpp:230) and choosePartFormat picks Packed only
when bytes < min_bytes_for_full_part_storage (src/Storages/MergeTree/MergeTreeData.cpp:5729-5731),
so at the default the part is always Full. The tag holds it there, and the test additionally
projects part_type so a wrong layout fails loudly instead of silently skipping the regression.
310 stateless tests carry this tag.

Closed during my own review

  • use_statistics / use_statistics_cache are randomized but gate only query-plan consumption
    (MergeTreeWhereOptimizer.cpp:130,165, optimizeJoin.cpp:354, MergeTreeData.cpp:901), not
    IMergeTreeDataPart::getEstimates, which serves the system.parts_columns estimates this test
    reads.
  • The registration half walks the stages after all of them exist, so it does not depend on the
    updated_header that is frozen earlier and is empty by design for MATERIALIZE STATISTICS.
  • Randomized max_insert_threads / max_block_size could in principle split a fixture into
    several active parts; closed empirically by a 50/50 randomized run with session randomization
    active.
  • My independent enumeration of the emitters into non-readonly stages matched the fix's set
    exactly, with no divergence.

Session id: cron:clickhouse-review-slot-49:20260727-015400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Answer
a Deterministic repro? Yes. Single-session pure SQL, no fuzzer and no concurrency: metadata-only ALTER MODIFY COLUMN e Int8 (from the allowed_conversions table, so no mutation is scheduled) followed by ALTER TABLE ... MATERIALIZE COLUMN e aborts every time on master with the exact CI stack. Preconditions asserted in the same run so the test cannot be vacuous: part_type = Wide, the part's own column type is still Enum8 after the ALTER, system.mutations is empty, metadata type is Int8, and statistics.packed is present in the part before the conversion.
b Root cause explained? Yes. MutateSomePartColumnsTask loads every statistics object from the source part and PartMergerWriter rebuilt every loaded object present in the block, with no selection step, so an object loaded only to be carried over was rebuilt against a block holding the column at the current metadata type while the object was built at the part's older type.
c Fix matches root cause? Yes. The mutation writer now builds only an explicitly selected set, mirroring MergeTask's existing statistics_to_build_by_part, and the columns a mutation genuinely rewrites are registered for recalculation. No widened bounds and no guard at the throw site. The test carries no-random-merge-tree-settings because randomized auto_statistics_types would add implicit statistics to every column and randomized ratio_of_defaults_for_sparse_serialization would perturb the exact uniq cardinalities it asserts; the Wide/full-storage precondition the regression needs is asserted in-test through part_type rather than assumed.
d Test intent preserved / new tests added? Yes. No existing test weakened or removed. One new stateless test with seven sections, covering all four affected mutation kinds plus the two paths this change could otherwise break.
e Demonstrated in both directions? Yes. All four carriers abort on the pristine master snapshot and pass on the fixed build; the type matrix aborts on master and passes fixed; the reference was recorded through the test runner against a server whose buildId() was checked equal to readelf -n.
f General across code paths? Yes. Both the all-columns and some-columns mutation paths are handled; MergeTask is untouched because it already selects correctly and is the reference shape; the load site is untouched deliberately (handing the part's own type to deserialize is correct for reads of that part). Exactly one MutateTask construction site exists, reached from MutatePlainMergeTreeTask and MutateFromLogEntryTask, so MergeTree, ReplicatedMergeTree and SharedMergeTree are covered by the same change.
g General across inputs? Yes. Verified on Enum8 -> Int8, Enum16 -> Int16, DateTime -> UInt32, Date -> UInt16, and through the Nullable, LowCardinality and Array wrappers; with uniq, basic, tdigest and countmin; and with implicit statistics from auto_statistics_types as well as an explicit STATISTICS clause. Compact and wide parts both exercised.
h Backward compatible? Yes. No format change, no new or changed setting, so no SettingsChangesHistory.cpp entry and no serialization versioning. The change is confined to which statistics a mutation recomputes.
i Invariants and contracts preserved? Yes. The full carried-plus-built set is still what gets serialized; the build set holds shared pointers into it, so building through the subset fills the objects that are written out, and nothing is dropped or added. Carried objects keep the new part's column type, so they are neither rebuilt nor freshened from table metadata, and the test asserts a carried statistic is still present, readable and usable after a pure MATERIALIZE INDEX. Existing ordering is preserved: the recalculation merge still runs after the removals in processStatisticsChanges.

Each half of the fix, and each of the two guards protecting the paths this change could break, was
pinned by a separate mutation test with the binary rebuilt and its Build ID confirmed to change:
reverting the selection half brings the abort back, reverting the registration half leaves stale
statistics content, and re-applying the rejected updated_header predicate makes both
MATERIALIZE STATISTICS and DELETE serialize empty statistics as expected.

50 randomized runs of the new test pass. A 152-test statistics-focused regression sweep produces the
same failure set on this build as on the pristine master snapshot.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @scanhex12 — could you review this? MutateSomePartColumnsTask loads every statistics object from the source part and the writer rebuilt every loaded one that appeared in the block, with no selection step, so an object loaded only to be carried over was rebuilt against a block holding the column at its current metadata type after a metadata-only ALTER MODIFY COLUMN; this adds the explicit build set MergeTask already has, and registers the three mutation kinds that rewrite a column without registering its statistics. It is the root-cause follow-up that #106963 deliberately deferred when it added the diagnostic.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7f642bc]

Summary: ✅


AI Review

Summary

This 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

  • [src/Interpreters/MutationsInterpreter.cpp:1551-1617, 1620-1649] [dismissed by author -- https://github.com/Build only the statistics a mutation is supposed to recompute #112009#discussion_r3655425623] columns_written_by_stages only feeds materialized_statistics. The skip-index and projection rebuild gates immediately above still key off updated_columns, changed_columns, and patch_updated_columns, so MATERIALIZE COLUMN and dependent MATERIALIZED rewrites remain invisible there. The current code therefore still hardlinks stale skip indexes / projections for those mutations, which can produce wrong pruning or stale projection reads even though the statistics half is fixed.
Final Verdict

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

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 27, 2026
Comment on lines +1612 to +1640
/// 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)

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.

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:

  1. UPDATE src = ... where m is a dependent MATERIALIZED column, or MATERIALIZE COLUMN m.
  2. The mutation adds a non-readonly stage that rewrites m, so this new columns_written_by_stages block correctly rebuilds m's statistics.
  3. updated_columns, changed_columns, and patch_updated_columns still do not contain m, so an index / projection defined on m is 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0ff719a

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (amd_release) infra — the job was killed before the build started: ci/praktika/secret.py:55 get_aws_ssm_parameter hit aws: [ERROR]: Connect timeout on endpoint URL: "https://ssm.us-east-1.amazonaws.com/" while fetching the chcache password, then ERROR: Job killed, exit code [1]. No compile error at all (FAILED: / : error: / ninja: build stopped all count 0). a fix task is created (investigating at full effort — fixing-PR link to follow here)
Docker server image, Docker keeper image, Install packages (amd_release), Compatibility check (amd_release), Upgrade check (amd_release), ClickBench (amd_release) DROPPED — dependency-dropped by the Build (amd_release) failure above, not independent failures same owner as Build (amd_release)

Not PR-caused: this PR's diff touches src/Interpreters/MutationsInterpreter.cpp,
src/Storages/MergeTree/MutateTask.cpp and one stateless test; it contains no build-system,
cmake or ci/ change, and the build never reached compilation. The same SSM condition killed
Build (*) jobs on several unrelated PRs in the same window, which is what shows it is
infrastructure rather than this diff.

Session id: cron:our-pr-ci-monitor:20260727-120000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Build (*) SSM failure on this pull request's CI finish ledger: #112279.

The aws ssm get-parameter call that killed the build was fetching the chcache password, which
nothing has read since 8012134d9d9e99 switched the build cache to sccache. #112279 deletes the
credential wiring, so the call is gone rather than made tolerant.

@PedroTadim PedroTadim self-assigned this Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.10% +0.10%
Branches 78.30% 78.40% +0.10%

Changed lines: Changed C/C++ lines covered: 34/34 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7f642bc

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
— no failed checks on this commit —

CI is fully finished on this commit with zero failing checks.

Session id: cron:our-pr-ci-monitor:20260729-043000

@PedroTadim

Copy link
Copy Markdown
Member

@hanfei1991 this seems good to me, can you give a final look? Shouldn't take long

@hanfei1991 hanfei1991 self-assigned this Jul 29, 2026
@hanfei1991
hanfei1991 added this pull request to the merge queue Jul 29, 2026
Merged via the queue into ClickHouse:master with commit e0ba854 Jul 29, 2026
178 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov could you apply v26.6-must-backport to this PR? Both 26.6 and 26.7 are aborting on the bug it fixes.

Two Stress aborts 38 minutes apart today, same Statistics.cpp -> MutateTask.cpp frames:

branch #106963 present this PR present signature
26.6 a3d20049 no no Bad cast from type DB::IColumn const* to DB::ColumnNullable const* (report)
26.7 2585c093 yes no Type mismatch when building statistics for column 'mtrl' (report)
master yes yes none since this merged

26.7 is the useful arm: it already has #106963 and still aborts. #106963 only replaces the opaque Bad cast with a worded LOGICAL_ERROR, which still aborts under a sanitizer, so backporting it alone would change 26.6's message and nothing else. This PR removes the cause, so it is the one that needs the label.

The 26.7 column mtrl comes from 02946_materialize_column_must_not_override_past_values.sql, whose MODIFY COLUMN mtrl Int64 MATERIALIZED 65432 keeps the type and so schedules no mutation stage; the abort is on the following MATERIALIZE COLUMN, one of the three unregistered emitters this PR fixes. That test declares no statistics; auto_statistics_generator() in tests/clickhouse-test randomizes auto_statistics_types and returns a non-empty sample about 70% of the time, which is where the uniq collector comes from. I traced that arm from source and CI rather than reproducing it locally, so treat it as the corroborating case; 26.6 is covered by this PR's own MATERIALIZE COLUMN reproducer.

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.

v26.6-must-backport expands to ['26.7', '26.6'] via select_backport_branches, which covers both failing branches and nothing older. pr-must-backport would also target 26.5, 26.3 and 25.8, which I have not seen failing.

Port simulation against today's tips, base pinned at this PR's merge parent:

  • 26.7: clean, 4 files, +187/-3.
  • 26.6: one conflict, in MutationsInterpreter.cpp only. patch_updated_columns does not exist there, so the resolution is to drop that clause and keep written_by_stage. Patch-updated columns arrive on 26.6 as READ_COLUMN, which already registers their statistics, so nothing is lost.

Symbol counts in the simulated 26.6 and 26.7 trees match master (statistics_to_build 6, columns_written_by_stages 3, written_by_stage 4) and the test lands at its full length, so neither port is a clean-merging no-op.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors 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

4 participants