Skip to content

Throw a diagnostic error on statistics column type mismatch instead of adapting - #106963

Merged
Avogar merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-statistics-uniq-nullable-build-mismatch
Jul 1, 2026
Merged

Avogar merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-statistics-uniq-nullable-build-mismatch

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

No related open issue. Found by the AST fuzzer / stress; CI failure reports are linked in the PR thread.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Description

Found by the AST fuzzer (around 110 rapid MODIFY COLUMN mutations followed by MATERIALIZE COLUMN on a table with implicit statistics, since auto_statistics_types defaults to "minmax, uniq"). The crash path is in MutateTask (PartMergerWriter::mutateOriginalPartAndPrepareProjections -> ColumnsStatistics::buildIfExists -> StatisticsUniq::build).

A statistics collector is created once from the declared column type. For uniq a Nullable type makes the collector the Null combinator (AggregateFunctionNullUnary), which assert_casts its input to ColumnNullable. During a MODIFY COLUMN type change a background mutation can feed the collector a column whose nullability does not match the metadata the collector was built from, so the cast aborted with an opaque Bad cast from type DB::IColumn const* to DB::ColumnNullable const* LOGICAL_ERROR.

This is not a user-visible behavior fix: it does not make the failing mutation succeed. The underlying mutation-pipeline / metadata mismatch remains. Instead of silently adapting the column inside StatisticsUniq::build, the check is moved up to the central point where the block column meets the collector, ColumnsStatistics::build and ColumnsStatistics::buildIfExists. When the block column type does not equal the statistics' declared type, we throw a LOGICAL_ERROR naming the column, the expected statistics type and the actual block type. This protects every statistics type that uses an aggregate function (not just uniq) and surfaces the underlying mismatch with diagnostics rather than hiding it behind a bad cast. In correct operation the three callers (insert, merge, mutate) all build statistics from the current metadata and feed a block of matching types, so the throw only fires on the genuine mismatch.

The merge path is also covered: ColumnStatistics::structureEquals now compares the declared statistics data type by name (getName()), so a part whose stored statistics type differs from the result column type is rebuilt instead of merged with a mismatched collector layout (name comparison rather than equals() so that custom types like Bool, which compares equal to UInt8, are still distinguished).

The unit test Statistics.UniqNullabilityMismatch (which asserted the old silent-adapt behavior) is repointed to Statistics.BuildTypeMismatchThrows, which asserts the new diagnostic throw and that the matching-type path still builds, plus Statistics.StructureEqualsConsidersDataType for the merge path. The throw assertion is guarded by #ifndef DEBUG_OR_SANITIZER_BUILD because constructing a LOGICAL_ERROR aborts the process in debug and sanitizer builds (it is treated as a failed assertion), mirroring gtest_memory_resize.cpp.

The end-to-end failure is a background metadata-version race between the collector's captured metadata version and the part column it reads; it is not deterministically reproducible from synchronous SQL (mutations apply in version order and the read pipeline always resolves the current metadata), so the regression test is a unit test.

Version info

  • Merged into: 26.7.1.350 (included in 26.7 and later)

StatisticsUniq builds its uniq aggregate collector once in the constructor
from the statistics' declared column type. When that type is Nullable, the
AggregateFunctionFactory wraps uniq in the Null combinator
(AggregateFunctionNullUnary), whose addBatchSinglePlace does
assert_cast<const ColumnNullable *>(columns[0]).

The column passed to build() can have a nullability that differs from the
declared type. Two known triggers:

  1. Mutation rebuild (MutateSomePartColumnsTask): statistics are loaded from
     the source part via loadStatistics() with collectors built from the part's
     stored (pre-change) type, while the mutation stream delivers the column in
     the post-change type. Statistics not listed in materialized_statistics keep
     the stale collector. buildIfExists() then feeds the new-type column to it.

  2. Asymmetric merge (MergeTask): parts created before and after a MODIFY
     COLUMN can carry different statistics structure. structureEquals only
     compares the set of statistics types, not column nullability, so a
     nullability-only change is not detected and the merge build step can feed a
     column whose nullability differs from the collector.

In both cases assert_cast aborts with
"Bad cast from type DB::IColumn const* to DB::ColumnNullable const*"
(a LOGICAL_ERROR), found by the AST fuzzer.

Fix: in StatisticsUniq::build, reconcile the column to what the collector
expects. The collector is the Null combinator iff getNestedFunction() != nullptr
(the same signal serialize()/deserialize() already use). Wrap the column with
makeNullable when the collector expects Nullable, or take the nested column when
it does not. uniq is a cardinality estimation, so wrapping a non-nullable column
adds an all-false null map and unwrapping drops only the null map, neither of
which changes the distinct-value count.

Other statistics types are not affected: StatisticsBasic, StatisticsMinMax and
StatisticsTDigest strip nullability at construction (removeNullable) and handle
it at build time, and StatisticsCountMinSketch uses nullability-agnostic virtual
IColumn methods (isNullAt/getDataAt). StatisticsUniq was the only type that
preserved declared nullability into an assert_cast at build time.

Adds a unit test (Statistics.UniqNullabilityMismatch) covering both directions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Unit test builds a StatisticsUniq collector on Nullable(Int32) and calls build() with a plain Int32 column. On master HEAD this aborts every time with the exact CIDB stack: throwBadAssertCast → AggregateFunctionNullUnary<false, true>::addBatchSinglePlace → StatisticsUniq::build → ColumnStatistics::build.
b Root cause explained? The collector is built once from the statistics' declared column type. A Nullable type wraps uniq in the Null combinator (AggregateFunctionNullUnary), whose addBatchSinglePlace does assert_cast<const ColumnNullable *>(columns[0]). During a pending MODIFY COLUMN mutation the per-part statistics are loaded with the pre-change-type collector while the stream delivers the post-change-type column; in an asymmetric merge structureEquals compares only the set of statistics types and misses a nullability-only change. So a non-nullable column reaches a Nullable collector (or vice versa) and the cast aborts.
c Fix matches root cause? Yes. build() now reconciles the column to what the collector actually expects, keyed on collector->getNestedFunction() (the same Null-combinator signal serialize/deserialize already use): makeNullable when the collector expects Nullable, take the nested column when it does not. It does not widen any bound or suppress randomization.
d Test intent preserved / new tests added? New unit test Statistics.UniqNullabilityMismatch covers both directions (Nullable collector + plain column → cardinality 100; non-nullable collector + Nullable column with NULLs → cardinality 86). No existing test was weakened.
e Both directions demonstrated? Yes. Probe test aborted on master HEAD; the same test passes after the fix. Verified unit_tests_dbms --gtest_filter=Statistics.UniqNullabilityMismatch = PASSED, and an SQL smoke test of MODIFY-nullability + mutation + ReplacingMergeTree OPTIMIZE FINAL scenarios all succeed and still estimate cardinality.
f Fix is general, not a narrow patch? Yes. Audited all sibling statistics build() paths: StatisticsBasic/StatisticsMinMax/StatisticsTDigest strip nullability at construction (removeNullable) and handle it at build; StatisticsCountMinSketch uses nullability-agnostic isNullAt/getDataAt. StatisticsUniq was the only type that carried declared nullability into an assert_cast at build time. The fix is at the build site that produces the bad cast, not a defensive guard masking an upstream bug — the divergence is legitimate (statistics are estimations spanning pending type changes).

Session id: cron:clickhouse-worker-slot-7:20260610-114000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @CurtizJ — could you review this? StatisticsUniq::build aborted with a Bad cast (IColumn -> ColumnNullable) when the runtime column's nullability differed from the statistics' declared type (pending MODIFY COLUMN mutation, or asymmetric merge that structureEquals misses). The fix reconciles the column to the collector using the same getNestedFunction() signal serialize/deserialize already use.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [75d59fe]

Summary: ✅


AI Review

Summary

This PR changes statistics rebuild/merge handling so a statistics collector declared for one column type is not fed or merged with data from another type. The current implementation guards ColumnsStatistics::build / buildIfExists, makes ColumnStatistics::structureEquals reject differently named declared types before merging loaded part statistics, and adds focused unit coverage for nullability, value-type, and Bool/UInt8 cases. I did not find any remaining correctness, safety, or metadata issues in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 10, 2026
When the declared statistics type is non-nullable but build() is fed a
Nullable column, the previous version unwrapped to the nested column,
which drops the null map. ColumnNullable stores a synthetic default at
NULL positions, so uniq (which ignores NULLs) would count that default
and inflate the distinct estimate by one.

Feed the nested column together with its null map via
addBatchSinglePlaceNotNull so NULL rows are skipped. The regression test
now asserts the true non-null cardinality (85, not 86).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (HEAD f814444)

# Question Answer
a Deterministic repro? Yes (unit-level). Statistics.UniqNullabilityMismatch builds a non-nullable uniq collector and feeds it a Nullable(Int32) column (100 rows, every 7th NULL). Before the null-map fix the collector counted the synthetic default stored at NULL rows → cardinality 86; correct value is 85. The original Bad-cast direction (Nullable collector + plain column) is also covered (→ 100).
b Root cause explained? StatisticsUniq builds its uniq collector once from the declared column type, so a Nullable declared type makes it the Null combinator and a non-nullable type makes it plain uniq. During a mutation/asymmetric-merge the column reaching build() can have the opposite nullability. The original PR reconciled this but, in the non-nullable-collector + Nullable-column direction, took getNestedColumnPtr() which drops the null map. ColumnNullable keeps a default value (e.g. 0) in the nested column for every NULL; uniq ignores NULLs, so that synthetic default gets counted whenever it is not otherwise present → distinct estimate inflated by one.
c Fix matches root cause? Yes. For the non-nullable-collector + Nullable-column path we now feed the nested column with its null map via addBatchSinglePlaceNotNull(..., ColumnNullable::getNullMapData().data(), ...), so NULL rows are skipped and the synthetic default is never counted. The opposite direction (Nullable collector + plain column) still wraps via makeNullable. No assertion bounds widened, no no-random-* tags.
d Test intent preserved / new tests added? Yes. The gtest now asserts the true non-null cardinality (85), fixing the previously baked-in wrong expectation (86) that the bot flagged. Both nullability-mismatch directions remain covered.
e Both directions demonstrated? Yes. With the fix the test PASSES (85 and 100). Reverting just this path to the null-map-dropping getNestedColumnPtr() and rebuilding makes the test FAIL with Which is: 86 vs 85u — i.e. the test catches exactly this regression. The pre-fix code also ABORTS with the original Bad cast IColumn -> ColumnNullable.
f Fix is general, not a narrow patch? Yes. Audited all sibling statistics build() paths: StatisticsBasic/MinMax/TDigest strip nullability at construction (removeNullable); StatisticsCountMinSketch is nullability-agnostic (isNullAt/getDataAt). StatisticsUniq was the only type carrying declared nullability into the aggregate call, and both of its mismatch directions are now handled. Not a symptom guard — the column is reconciled to what the collector requires before aggregation.

Session id: cron:clickhouse-worker-slot-5:20260610-134100

@groeneai

Copy link
Copy Markdown
Collaborator Author

Good catch, fixed in f814444.

The non-nullable-collector + Nullable-column path now preserves the null map instead of unwrapping: it feeds the nested column together with ColumnNullable::getNullMapData() via addBatchSinglePlaceNotNull, so NULL rows are skipped and the synthetic default stored at NULL positions is no longer counted.

The regression test now asserts 85 (the true non-null distinct count for 100 rows with every 7th NULL), not 86. Reverting just this path to the previous getNestedColumnPtr() and rebuilding makes the test fail with Which is: 86 vs 85u, so it now guards exactly this case. The opposite direction (Nullable collector + plain column) still wraps via makeNullable and reports 100 as before.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI status for f814444: two red checks, both unrelated to this PR (which only changes StatisticsUniq null-map handling):

  • Stateless tests (arm_asan_ubsan, azure, parallel) / 03742_nested_loop_join_long: the known 2026-06-09 Azure infrastructure outage window (many unrelated azure-variant tests failed together), not flakiness in this test or PR.
  • Stress test (amd_debug) / Logical error: Table ... not found in catalog (STID: 3215-370f): a separate chronic trunk bug already fixed by merged PR Fix logical error when table is dropped before distributed plan task deserialization #106944; this run predates propagation of that fix.

Finish Workflow and Mergeable Check are green.

@Avogar Avogar self-assigned this Jun 22, 2026
@Avogar

Avogar commented Jun 23, 2026

Copy link
Copy Markdown
Member

@groeneai Please, try to write SQL/bash test that reproduces the bug

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Avogar I tried hard but could not get a deterministic SQL/bash repro. The crash is a background-task metadata-version race, not something a single SQL session can force.

What I checked:

  • Both original crash stacks (AST fuzzer on master 2026-05-27, Stress arm_asan_ubsan 2026-06-17) abort entirely inside a background ThreadPool::worker: MutateSomePartColumnsTask -> PartMergerWriter::mutateOriginalPartAndPrepareProjections -> buildIfExists -> StatisticsUniq::build. No foreground query is on either stack.
  • I built an instrumented binary that logs whenever build() sees a collector/column nullability mismatch, and ran ~30 scenarios: MODIFY both directions (with/without DEFAULT), OPTIMIZE/FINAL/DEDUPLICATE, DELETE and lightweight DELETE, UPDATE, stacked async mutations with STOP/START MERGES, DETACH/MODIFY/ATTACH, ATTACH PARTITION FROM, vertical merge, LowCardinality(Nullable), explicit and auto_statistics_types implicit stats, plus 6-way concurrent insert+modify+optimize+update loops with the stress THREAD_FUZZER_* env enabled. The mismatch log never fired.

Why it does not reproduce synchronously:

  • Mutations apply strictly in version order per table, so a MODIFY always rewrites the part to the new type before any later mutation reads it.
  • The read pipeline (merge and mutation) resolves the column through the current metadata snapshot / alter conversions, so the read column nullability matches current metadata, and loadStatistics() builds the collector from the part's columns.txt, updated in lockstep.
  • canSkipConversionToNullable, the one path that leaves a part physically old-typed under new metadata, explicitly bails when the column has any statistic, so "skipped rewrite" and "has a uniq stat" are mutually exclusive.

So the window only opens as a metadata-version-skew TOCTOU between a background task's collector and the part it reads, which is why only the stress and AST fuzzers hit it.

The fix is validated bidirectionally by the unit test Statistics.UniqNullabilityMismatch (reverting the null-map path makes it fail with 86 vs 85). For a stateless test I see two options:

  1. A deterministic .sql test gated by a new failpoint that forces the nullability skew, in the style of 04295_105912_modify_column_to_nullable_with_statistics.sql (which uses mt_mutate_task_can_skip_conversion_to_nullable_force_null_column_desc). This needs a small failpoint added to StatisticsUniq::build.
  2. Keep only the unit test.

I lean towards 1 since it gives a deterministic regression test, but it adds a failpoint to production code, so your call. Which do you prefer?

@Avogar

Avogar commented Jun 24, 2026

Copy link
Copy Markdown
Member

@groeneai include the link to the failure that you are trying to fix, so I can look at it

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Avogar Links to the failures this fixes (Bad cast ... IColumn -> ColumnNullable in StatisticsUniq::build, STID 3524-3a4b):

Both abort in a background mutate task:

throwBadAssertCast
AggregateFunctionNullUnary<false, true>::addBatchSinglePlace   AggregateFunctionNull.h:442
StatisticsUniq::build                                          StatisticsUniq.cpp:47
ColumnStatistics::build                                        Statistics.cpp
ColumnsStatistics::buildIfExists
PartMergerWriter::mutateOriginalPartAndPrepareProjections      MutateTask.cpp

The uniq collector is built from the column's declared (Nullable) type, so it is the Null combinator that assert_casts its input to ColumnNullable, while the part column read in the mutation stream is non-nullable (or vice versa), so the cast aborts.

@Avogar

Avogar commented Jun 24, 2026

Copy link
Copy Markdown
Member

The crash is real — the AST fuzzer reproduced it via ~110 rapid MODIFY COLUMN mutations followed by MATERIALIZE COLUMN on a table with implicit statistics (auto_statistics_types defaults to "minmax, uniq"). The crash path is in MutateTask (not MergeTask as the PR description says).

However, I think the fix should be different:

  1. Wrong level: Fixing inside StatisticsUniq::build only protects one statistics type. Other statistics types that use aggregate functions could have the same issue. The fix should be in ColumnsStatistics::buildIfExists / ColumnsStatistics::build, which is where the block column meets the statistics collector.

  2. Don't silently adapt the column type — throw instead. We don't fully understand how the mutation pipeline produces a column whose type doesn't match the metadata. Silently fixing the mismatch hides a bug somewhere in the mutation pipeline or metadata management. A proper exception with diagnostic information would help us find and fix the root cause.

Something like this in ColumnsStatistics::buildIfExists:

void ColumnsStatistics::buildIfExists(const Block & block)
{
    for (const auto & [column_name, stat] : *this)
    {
        if (!block.has(column_name))
            continue;

        const auto & col = block.getByName(column_name);
        auto stats_data_type = stat->getDataType();

        if (!col.type->equals(*stats_data_type))
            throw Exception(
                ErrorCodes::LOGICAL_ERROR,
                "Type mismatch when building statistics for column '{}': "
                "statistics expect type {} but block has type {}",
                column_name,
                stats_data_type->getName(),
                col.type->getName());

        stat->build(col.column);
    }
}

And the same check in ColumnsStatistics::build.

This will give us a clear error message with the column name, the expected type and the actual type, making it much easier to trace the root cause in the mutation pipeline.

…f adapting

Move the type/nullability-mismatch handling out of StatisticsUniq::build and
into the central ColumnsStatistics::build and ColumnsStatistics::buildIfExists,
where the block column meets the statistics collector. This protects every
statistics type that uses an aggregate function, not just uniq.

Per maintainer review (PR ClickHouse#106963): do not silently adapt the column. The
statistics collector is created once from the declared column type (a Nullable
type makes uniq the Null combinator that casts its input to ColumnNullable). If
the block column has a different type the collector mis-casts and aborts with an
opaque "Bad cast from type DB::IColumn const* to DB::ColumnNullable const*".

A type mismatch here means the mutation pipeline or metadata management produced
a column that disagrees with the metadata the statistics were built from (e.g. a
pending MODIFY COLUMN type change observed by a background mutation). That is an
upstream bug. Surface it with a clear LOGICAL_ERROR naming the column, the
expected statistics type and the actual block type, instead of masking it.

The crash was found by the AST fuzzer (~110 rapid MODIFY COLUMN mutations
followed by MATERIALIZE COLUMN on a table with implicit statistics; the path is
in MutateTask, not MergeTask). The unit test Statistics.UniqNullabilityMismatch
asserted the old silent-adapt behavior; it is repointed to
Statistics.BuildTypeMismatchThrows, which asserts the new diagnostic throw (in
release builds; debug/sanitizer builds abort on LOGICAL_ERROR construction) and
that the matching-type path still builds.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai groeneai changed the title Fix Bad cast in StatisticsUniq::build on column nullability mismatch Throw a diagnostic error on statistics column type mismatch instead of adapting Jun 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes at the code-path level: the new unit test Statistics.BuildTypeMismatchThrows deterministically drives a type-mismatched column into ColumnsStatistics::build/buildIfExists. The end-to-end SQL repro is a background metadata-version race (mutations apply in version order, the read pipeline always resolves current metadata), not deterministically reproducible from synchronous SQL, as discussed above.
b Root cause explained? A statistics collector is built once from the declared column type. For uniq a Nullable type makes it the Null combinator (AggregateFunctionNullUnary) that assert_casts its input to ColumnNullable. During a MODIFY COLUMN change a background mutation feeds a column of the other nullability, so the cast aborts (Bad cast ... ColumnNullable).
c Fix matches root cause? Yes. The mismatch is detected at the central point where the block column meets the collector (ColumnsStatistics::build and buildIfExists), before the column reaches the aggregate function, and a diagnostic LOGICAL_ERROR is thrown instead of the column being silently adapted.
d Test intent preserved / new tests added? The old Statistics.UniqNullabilityMismatch asserted the silent-adapt behavior, which is gone; it is repointed to Statistics.BuildTypeMismatchThrows, which asserts the new throw (column name + expected/actual type) and that the matching-type path still builds. No coverage removed.
e Both directions demonstrated? Without the fix the mismatched column reaches StatisticsUniq::build and aborts with the bad cast; with the fix ColumnsStatistics::build/buildIfExists throws the diagnostic first. The unit test exercises both the throw (release) and the matching-type success path.
f Fix is general across code paths? Yes. The check was moved out of StatisticsUniq::build into ColumnsStatistics::build and ColumnsStatistics::buildIfExists, so every statistics type that uses an aggregate function is protected, not just uniq. The three callers (insert, merge, mutate) all build statistics from current metadata and feed a matching block, so the throw fires only on the genuine mismatch.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The check is !col.type->equals(*stats_data_type), which compares full types, so it covers every wrapper (Nullable, LowCardinality, LC(Nullable), Array, Map, Const) and every column type uniformly, not just the Nullable(Int32) variant the fuzzer hit.
h Backward compatible? Yes. No setting default, on-disk, wire, or replication format change; SettingsChangesHistory.cpp not touched. The only behavior change is that an opaque abort becomes a clear LOGICAL_ERROR (both fail the mutation; the new one is diagnostic).
i Invariants and contracts preserved? Yes. The check is a strict precondition for stat->build(col.column): the collector requires a column of its declared type. buildIfExists keeps skipping columns absent from the block. Verified all three call sites pass a block whose column types match the metadata the statistics were built from in correct operation.

Session id: cron:clickhouse-worker-slot-1:20260624-180100

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Avogar Done, pivoted as you suggested.

  • Moved the handling out of StatisticsUniq::build (reverted that change) into the central ColumnsStatistics::buildIfExists and ColumnsStatistics::build, so it covers every statistics type that uses an aggregate function, not just uniq.
  • It now throws a diagnostic LOGICAL_ERROR naming the column, the expected statistics type and the actual block type, instead of silently adapting the column, so the underlying mutation-pipeline / metadata mismatch is surfaced rather than hidden:
if (!col.type->equals(*stats_data_type))
    throw Exception(ErrorCodes::LOGICAL_ERROR,
        "Type mismatch when building statistics for column '{}': "
        "statistics expect type {} but block has type {}",
        column_name, stats_data_type->getName(), col.type->getName());
  • Repointed the unit test to Statistics.BuildTypeMismatchThrows (asserts the throw + that the matching-type path still builds). The throw assertion is guarded by #ifndef DEBUG_OR_SANITIZER_BUILD since constructing a LOGICAL_ERROR aborts in debug/sanitizer builds, mirroring gtest_memory_resize.cpp.
  • Corrected the PR description: the crash path is in MutateTask, not MergeTask.

In correct operation the three callers (insert, merge, mutate) all build statistics from current metadata and feed a matching block, so the throw fires only on the genuine mismatch.

Comment thread src/Storages/Statistics/Statistics.cpp Resolved
The build-time guard added in the previous commit fires only when statistics
are rebuilt from a block. The merge path in MergeTask takes a different route:
when ColumnStatistics::structureEquals returns true it merges an already-loaded
part statistic into the result collector (ColumnStatistics::merge) instead of
scheduling a rebuild, so a mismatched loaded statistic never reaches the build
guard.

structureEquals previously compared only the set of statistics kinds, not the
declared data type. During a rolling MODIFY COLUMN that pairs a result collector
created from Nullable(Int32) with a source-part statistic loaded from Int32; the
per-statistics merge (e.g. StatisticsUniq::merge) only checks the statistics
class, so aggregate states with incompatible collector layouts are merged as if
they matched.

Include the declared data type in structureEquals so a type or nullability
difference is treated as a different structure. The single caller
(MergeTask::prepareGatheredColumns) then reschedules a rebuild for that part,
which goes through the build-time type-mismatch guard. The common case (same
stored and current type) is unchanged, so no extra rebuilds there. Reported by
review on PR ClickHouse#106963.

Extends the unit test with Statistics.StructureEqualsConsidersDataType, which
asserts structureEquals returns true for equal declared types and false for a
nullability-only difference in both directions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the follow-up commit (77e0a64, merge-path structureEquals fix).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The merge-path gap is exercised deterministically at unit level: Statistics.StructureEqualsConsidersDataType shows structureEquals now returns false for an Int32 vs Nullable(Int32) pair (so MergeTask reschedules a rebuild instead of merging). The end-to-end SIGABRT remains a background metadata-version race, not synchronously SQL-reproducible (established + communicated earlier on this PR).
b Root cause explained? ColumnStatistics::structureEquals compared only the set of statistics kinds, not stats_desc.data_type. Its sole caller (MergeTask::prepareGatheredColumns, MergeTask.cpp:794) merges a loaded part statistic into the result collector when it returns true. A rolling MODIFY COLUMN thus pairs a Nullable(Int32) result collector with an Int32-loaded source stat; StatisticsUniq::merge checks only the class, so incompatible aggregate-state layouts are merged. This path never reaches the build-time checkColumnTypeMatchesStatistics guard.
c Fix matches root cause? Include the declared data_type in structureEquals so a type/nullability difference returns false. The caller then takes the rebuild branch (cloneEmpty()), which runs through the build-time guard. Directly closes the merge bypass, no symptom masking.
d Test intent preserved / new tests added? Kept Statistics.BuildTypeMismatchThrows (build-time guard). Added Statistics.StructureEqualsConsidersDataType asserting equal declared types compare equal (common case keeps merging) and a nullability-only difference compares unequal both directions. No coverage weakened.
e Both directions demonstrated? Unit test: equal type -> true (merge, no needless rebuild); mismatched type -> false (rebuild -> guard). Combined with the prior commit, the mismatched path now throws a clean LOGICAL_ERROR instead of Bad cast ... ColumnNullable SIGABRT.
f Fix is general across code paths? Both statistics merge call sites checked: MergeTask.cpp:794 merges a disk-loaded part stat (now gated by the type-aware structureEquals); MergeTask.cpp:2897 (mergeBuiltStatistics) merges freshly built stats whose declared types match by construction (both from the same current metadata snapshot, via cloneEmpty()). structureEquals change is central (one caller, all stat kinds), not uniq-specific.
g Fix generalizes across inputs (params/datatypes/wrappers)? structureEquals uses IDataType::equals, which distinguishes all wrappers (Nullable, LowCardinality, LC(Nullable), Array, Map, Const, plain) and inner types. The comparison is null-pointer tolerant (a missing data_type on either side is handled before deref). Tested both nullability directions.
h Backward compatible? Yes. No setting, on-disk, or wire-format change. structureEquals is an in-memory merge-vs-rebuild decision; stricter equality only triggers a rebuild for genuinely mismatched parts (the correct, safe action) and leaves the steady-state case (stored type == current type) merging as before. No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? structureEquals's contract (true iff the two statistics can be merged without a rebuild) is the exact precondition ColumnStatistics::merge / StatisticsUniq::merge rely on (compatible collector layouts). The change strengthens it to also require type compatibility, restoring that invariant. The single caller already handles false via cloneEmpty() rebuild.

Session id: cron:clickhouse-worker-slot-2:20260624-185400

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the flaky test_quorum_inserts_parallel/test.py::test_parallel_quorum_actually_quorum (seen on this PR's CI, not caused by it) created: #108433

Comment thread src/Storages/Statistics/Statistics.cpp Outdated
Comment on lines +168 to +171
if (static_cast<bool>(lhs_type) != static_cast<bool>(rhs_type))
return false;
if (lhs_type && !lhs_type->equals(*rhs_type))
return false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why not just this? Also, I think better to compare type names because of custom types like Bool that is compared as UInt8 in quals

Suggested change
if (static_cast<bool>(lhs_type) != static_cast<bool>(rhs_type))
return false;
if (lhs_type && !lhs_type->equals(*rhs_type))
return false;
if (!lhs_type || !rhs_type || lhs_type->getName() != rhs_type->getName())
return false;

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.

@Avogar Applied your suggestion in b960d3e: structureEquals now compares getName() instead of equals().

You are right about Bool: it is stored as UInt8 and shares its typeid, so equals() returns true (the numeric equals() is typeid(rhs) == typeid(*this)), while getName() keeps them distinct. Comparing names is therefore strictly more precise here, and the declared data_type is never null on a constructed ColumnStatistics (it is dereferenced unconditionally elsewhere, e.g. in serialize), so the !lhs_type || !rhs_type guard is just defensive.

Extended the unit test Statistics.StructureEqualsConsidersDataType with a Bool vs UInt8 case: it fails with the old equals() comparison (treats them as equal) and passes with the name comparison.

void checkColumnTypeMatchesStatistics(const String & column_name, const ColumnStatisticsPtr & stat, const DataTypePtr & column_type)
{
auto stats_data_type = stat->getDataType();
if (!column_type->equals(*stats_data_type))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Better to compare type names as I commented in previous comment (if I am wrong, explain)

@Avogar

Avogar commented Jun 25, 2026

Copy link
Copy Markdown
Member

Also I believe it's not a bugfix anymore, it's should be not for changelog as we just change one error to another, better one, but the bug remains I believe. Or I am wrong?

ColumnStatistics::structureEquals compared the declared data_type with
IDataType::equals(), which treats a custom-named type as equal to its
underlying type: Bool is stored as UInt8 and shares its typeid, so
Bool->equals(UInt8) is true. The serialized statistics layout still
differs, so a Bool<->UInt8 change on a column carrying statistics would
not force a merge-time rebuild and could merge incompatible collectors.

Compare getName() instead, so any declared-type difference (including a
custom name) is treated as a different structure and the merge path
rebuilds the statistics. The unit test now also covers Bool vs UInt8.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes (unit). Statistics.StructureEqualsConsidersDataType with a Bool vs UInt8 pair fails on demand with the old equals() comparison.
b Root cause explained? Bool is registered as DataTypeUInt8 with only a custom name; numeric IDataType::equals() is typeid(rhs) == typeid(*this), so Bool.equals(UInt8) is true. structureEquals used equals(), so a Bool<->UInt8 declared-type change was treated as the same structure and the merge path merged collectors with different serialized layouts instead of rebuilding.
c Fix matches root cause? Yes. Compare getName() instead of equals(); the custom name distinguishes Bool from UInt8, so any declared-type difference forces a rebuild (which then passes through the build-time guard).
d Test intent preserved / new tests added? Existing nullability-flip and matching-type assertions kept; added Bool vs UInt8 (both directions) plus Bool==Bool. No coverage weakened.
e Both directions demonstrated? Yes. With old equals(): Bool.structureEquals(UInt8) returns true -> test FAILS. With getName(): returns false -> test PASSES. Rebuilt (Build ID changed), ran both ways.
f Fix is general across code paths? Yes. structureEquals has one caller (MergeTask merge-vs-rebuild). The build-from-block path is already guarded by checkColumnTypeMatchesStatistics (also equals()-based, but there a Bool/UInt8 block column is layout-compatible with a UInt8 collector and must not abort a legitimate mutation, so equals() is correct there).
g Fix generalizes across inputs? Yes. getName() distinguishes any custom-named or wrapped type (Bool, Nullable, LowCardinality, Enum, etc.); equal names still merge (no needless rebuild in the common case).
h Backward compatible? Yes. In-memory merge-vs-rebuild decision only; no setting, on-disk, or wire format change. Steady-state merges (equal types) are unchanged.
i Invariants and contracts preserved? Yes. structureEquals only ever converts a previously-unsafe merge into a safe rebuild; data_type is invariant non-null on a constructed ColumnStatistics, and the null guards are defensive. The kinds-set comparison is unchanged.

Session id: cron:clickhouse-worker-slot-0:20260625-134800

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Avogar You are right. This is no longer a user-visible bug fix: the failing mutation still fails, we just replace an opaque Bad cast with a clear diagnostic LOGICAL_ERROR and leave the underlying mutation-pipeline/metadata mismatch in place (on purpose, so it can be root-caused). Changed the category to Not for changelog and removed the changelog entry. I cannot drop the pr-bugfix label myself (fork contributors lack label permissions), so it may need clearing on your side.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b960d3e

Every failure below has an owner. Neither is caused by this PR's diff: the diagnostic-throw guard message Type mismatch when building statistics appears 0 times in either job's logs, and this fixup only changes structureEquals to compare type names.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found shutdown/teardown deadlock; the hung query was a fuzzed 04357_set_skip_index_lowcardinality_hastoken_like.sql (ast_fuzzer, ~1283s) #101680 + #105905 (ours, open)
Stress test (arm_asan_ubsan) ERROR, no server logs uploaded (initial/final/main all absent), externally cancelled at the stress time limit while progressing; no crash/sanitizer/LOGICAL_ERROR. No flushed final log is consistent with a shutdown deadlock (the condition #101680 targets) #101680 + #105905 (ours, open)

Session id: cron:clickhouse-worker-slot-3:20260625-190000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b960d3e

CI fully finished on this head (Finish Workflow pass, Mergeable aggregator complete, >3h ingestion buffer). Every failure below has an owner. Neither is caused by this PR's diff (it only touches src/Storages/Statistics/StatisticsUniq.{h,cpp}).

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found deadlock (chronic trunk family, 447 distinct PRs / 330 master hits in 30d; unrelated to the statistics diff) #101680 / #105905 (ours, open)
Stress test (arm_asan_ubsan) job-level ERROR with no test rows / logs = hung-check watchdog kill on the same commit, same signature #101680 / #105905 (ours, open)

Session id: cron:our-pr-ci-monitor:20260625-200000

… guard test

STID 2404-35eb is the value-type sibling of the nullability mismatch (STID
3524-3a4b) this PR already guards: a uniq statistics collector declared on
Int64 (AggregateFunctionUniq<long>, column ColumnVector<long>) was fed a
ColumnDecimal<Decimal256> block during a mutation statistics rebuild, aborting
with Bad cast ColumnDecimal<Decimal256> to ColumnVector<long> inside
addBatchSinglePlaceNotNull. checkColumnTypeMatchesStatistics uses
column_type->equals(stats_data_type), so it already covers the value-type
dimension as well as nullability, but BuildTypeMismatchThrows only exercised
the nullability case. Add Int64/Decimal256 cases via both build and
buildIfExists, plus a matching-Decimal256 positive path, so the value-type
dimension is covered by a test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Added a value-type regression case to BuildTypeMismatchThrows for STID 2404-35eb: the same bad-cast aborted as ColumnDecimal<Decimal256> to ColumnVector<long> (an Int64-declared uniq collector fed a Decimal256 block during a mutation statistics rebuild) instead of the ColumnNullable form. checkColumnTypeMatchesStatistics already covers it via equals(), but the test only exercised the nullability dimension; the new case asserts the guard fires for Int64/Decimal256 through both build and buildIfExists, plus a matching-Decimal256 positive path.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107861&sha=832bd36b10fdd43a49b019f29bc891f5366c6c2f&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 (Stress test (arm_tsan), 2026-06-28).

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Jun 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.40% +0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 96/96 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@Avogar
Avogar added this pull request to the merge queue Jul 1, 2026
Merged via the queue into ClickHouse:master with commit ae7526a Jul 1, 2026
169 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
pull Bot pushed a commit to TCeason/ClickHouse that referenced this pull request Jul 29, 2026
`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.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…f adapting

Move the type/nullability-mismatch handling out of StatisticsUniq::build and
into the central ColumnsStatistics::build and ColumnsStatistics::buildIfExists,
where the block column meets the statistics collector. This protects every
statistics type that uses an aggregate function, not just uniq.

Per maintainer review (PR ClickHouse#106963): do not silently adapt the column. The
statistics collector is created once from the declared column type (a Nullable
type makes uniq the Null combinator that casts its input to ColumnNullable). If
the block column has a different type the collector mis-casts and aborts with an
opaque "Bad cast from type DB::IColumn const* to DB::ColumnNullable const*".

A type mismatch here means the mutation pipeline or metadata management produced
a column that disagrees with the metadata the statistics were built from (e.g. a
pending MODIFY COLUMN type change observed by a background mutation). That is an
upstream bug. Surface it with a clear LOGICAL_ERROR naming the column, the
expected statistics type and the actual block type, instead of masking it.

The crash was found by the AST fuzzer (~110 rapid MODIFY COLUMN mutations
followed by MATERIALIZE COLUMN on a table with implicit statistics; the path is
in MutateTask, not MergeTask). The unit test Statistics.UniqNullabilityMismatch
asserted the old silent-adapt behavior; it is repointed to
Statistics.BuildTypeMismatchThrows, which asserts the new diagnostic throw (in
release builds; debug/sanitizer builds abort on LOGICAL_ERROR construction) and
that the matching-type path still builds.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The build-time guard added in the previous commit fires only when statistics
are rebuilt from a block. The merge path in MergeTask takes a different route:
when ColumnStatistics::structureEquals returns true it merges an already-loaded
part statistic into the result collector (ColumnStatistics::merge) instead of
scheduling a rebuild, so a mismatched loaded statistic never reaches the build
guard.

structureEquals previously compared only the set of statistics kinds, not the
declared data type. During a rolling MODIFY COLUMN that pairs a result collector
created from Nullable(Int32) with a source-part statistic loaded from Int32; the
per-statistics merge (e.g. StatisticsUniq::merge) only checks the statistics
class, so aggregate states with incompatible collector layouts are merged as if
they matched.

Include the declared data type in structureEquals so a type or nullability
difference is treated as a different structure. The single caller
(MergeTask::prepareGatheredColumns) then reschedules a rebuild for that part,
which goes through the build-time type-mismatch guard. The common case (same
stored and current type) is unchanged, so no extra rebuilds there. Reported by
review on PR ClickHouse#106963.

Extends the unit test with Statistics.StructureEqualsConsidersDataType, which
asserts structureEquals returns true for equal declared types and false for a
nullability-only difference in both directions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…q-nullable-build-mismatch

Throw a diagnostic error on statistics column type mismatch instead of adapting
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-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants