Repository navigation
Conversation
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]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-7:20260610-114000 |
|
cc @hanfei1991 @CurtizJ — could you review this? |
|
Workflow [PR], commit [75d59fe] Summary: ✅
AI ReviewSummaryThis 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 Final VerdictStatus: ✅ Approve |
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]>
Pre-PR validation gate (HEAD f814444)
Session id: cron:clickhouse-worker-slot-5:20260610-134100 |
|
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 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 |
|
CI status for f814444: two red checks, both unrelated to this PR (which only changes
Finish Workflow and Mergeable Check are green. |
|
@groeneai Please, try to write SQL/bash test that reproduces the bug |
|
@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:
Why it does not reproduce synchronously:
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
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? |
|
@groeneai include the link to the failure that you are trying to fix, so I can look at it |
|
@Avogar Links to the failures this fixes (
Both abort in a background mutate task: The |
|
The crash is real — the AST fuzzer reproduced it via ~110 rapid However, I think the fix should be different:
Something like this in 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 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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260624-180100 |
|
@Avogar Done, pivoted as you suggested.
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());
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. |
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]>
|
Pre-PR validation gate for the follow-up commit (77e0a64, merge-path Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260624-185400 |
|
Fixing PR for the flaky |
| if (static_cast<bool>(lhs_type) != static_cast<bool>(rhs_type)) | ||
| return false; | ||
| if (lhs_type && !lhs_type->equals(*rhs_type)) | ||
| return false; |
There was a problem hiding this comment.
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
| 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; |
There was a problem hiding this comment.
@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)) |
There was a problem hiding this comment.
Better to compare type names as I commented in previous comment (if I am wrong, explain)
|
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260625-134800 |
|
@Avogar You are right. This is no longer a user-visible bug fix: the failing mutation still fails, we just replace an opaque |
CI finish ledger - b960d3eEvery failure below has an owner. Neither is caused by this PR's diff: the diagnostic-throw guard message
Session id: cron:clickhouse-worker-slot-3:20260625-190000 |
CI finish ledger - b960d3eCI 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
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]>
|
Added a value-type regression case to 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). |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 96/96 (100.00%) | Lost baseline coverage: none · Uncovered code |
`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.
…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]>
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]>
…q-nullable-build-mismatch Throw a diagnostic error on statistics column type mismatch instead of adapting
No related open issue. Found by the AST fuzzer / stress; CI failure reports are linked in the PR thread.
Changelog category (leave one):
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 COLUMNmutations followed byMATERIALIZE COLUMNon a table with implicit statistics, sinceauto_statistics_typesdefaults to"minmax, uniq"). The crash path is inMutateTask(PartMergerWriter::mutateOriginalPartAndPrepareProjections->ColumnsStatistics::buildIfExists->StatisticsUniq::build).A statistics collector is created once from the declared column type. For
uniqa Nullable type makes the collector theNullcombinator (AggregateFunctionNullUnary), whichassert_casts its input toColumnNullable. During aMODIFY COLUMNtype 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 opaqueBad 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::buildandColumnsStatistics::buildIfExists. When the block column type does not equal the statistics' declared type, we throw aLOGICAL_ERRORnaming the column, the expected statistics type and the actual block type. This protects every statistics type that uses an aggregate function (not justuniq) 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::structureEqualsnow 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 thanequals()so that custom types likeBool, which compares equal toUInt8, are still distinguished).The unit test
Statistics.UniqNullabilityMismatch(which asserted the old silent-adapt behavior) is repointed toStatistics.BuildTypeMismatchThrows, which asserts the new diagnostic throw and that the matching-type path still builds, plusStatistics.StructureEqualsConsidersDataTypefor the merge path. The throw assertion is guarded by#ifndef DEBUG_OR_SANITIZER_BUILDbecause constructing aLOGICAL_ERRORaborts the process in debug and sanitizer builds (it is treated as a failed assertion), mirroringgtest_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
26.7.1.350(included in26.7and later)