Repository navigation
Conversation
`IDataType::equals` compares the representation, so `Bool` equals `UInt8` at every nesting level. Every gate that skips a conversion on `equals` let the bytes 2..255 reach a `Bool` column, where they print `true` but fail `= true` and survive `DELETE ... WHERE b = true`: - `INSERT ... SELECT` (also MV `TO`, refreshable MV, views) added no `CAST`; - `ALTER MODIFY COLUMN UInt8 -> Bool` was metadata-only and old parts were read raw; - `ATTACH/REPLACE/MOVE PARTITION FROM` accepted a `UInt8` source column; - `INSERT` through a `Distributed` table declaring `UInt8` over a shard `Bool` sent the block unconverted. Add `isIdentityConversion(from, to)` to `DataTypes/Utils`: `from.equals(to)` and no position where `to` has `Bool` and `from` does not (`JSON` typed paths and `Variant` alternatives are opaque, as `CAST` copies the former as is and matches the latter by name). Use it instead of `equals` / `blocksHaveEqualStructure` in `makeConvertingActions`, `isTrueMetadataOnlyConversion`, the part-read conversion (`IMergeTreeReader::performRequiredConversions`, `convertRequiredExpressions`), the mutation's index rebuild (`MutationsInterpreter`, `MutateTask`), the skip-index staleness check, `canSkipConversionToNullable`, view inlining, trivial view pushdown and the view `ORDER BY ... LIMIT` pushdown, `Merge` and MV PREWHERE eligibility, the MV read, the nested `CAST` identity in `FunctionCast::prepareImpl`, `DistributedSink`'s `adoptBlock` and the async `Distributed` send (`writeRemoteConvert`); and add a per-column check to `checkStructureAndGetMergeTreeData`. Consequences, all the documented `CAST` semantics: `MODIFY COLUMN UInt8 -> Bool` is now a mutation, like `UInt8 -> Enum8`, and is refused on sorting or partition key columns and on a column a projection aggregates, filters by or sorts by through an expression or a subcolumn, unless the projection is keyed on the column itself (the mutation keeps the parts of a projection it does not rebuild); `ATTACH/REPLACE/MOVE PARTITION` from a `UInt8` column into a `Bool` one is refused, like `Int8`; `Bool -> UInt8` stays metadata-only. Unchanged: the `equals` shortcut of `castColumn` (so `Distributed` reads, `Buffer`, format type hints and the native protocol keep master's behaviour), `AggregateFunction(f, Bool)` states, `SimpleAggregateFunction(f, Bool)`, and MATERIALIZED columns computed from the column (as after any rewriting MODIFY COLUMN). `04871` case 19 now builds its stale-index fixture by attaching a `Tuple(x Bool)` part into `Tuple(x UInt8)`, the direction that still attaches. Closes ClickHouse#130894. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the isIdentityConversion doc and drop two comments that narrate the new code. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 8 rounds, 19 findings) plus seven cold reviews of my own (13 findings). Bounce cap reached: published as is after the last fix round; no AGREEd finding is left open.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20261113-204000 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20261113-202300 |
|
Workflow [PR], commit [0a7cad0] Summary: ❌
AI ReviewSummaryThe PR makes Findings❌ Blockers
Tests
Both failures were reproduced using the PR's CI fast-test binary, which reports the reviewed merge commit as Final Verdict❌ Block. Protect retained projections and TTL metadata across the affected conversions, and add the two focused regressions. These concerns remain in this summary only; the author's dismissals were not challenged again in their inline threads. |
`MODIFY COLUMN v Nullable(Bool)` over `Nullable(UInt8)` now rewrites the part, because `UInt8 -> Bool` is a real conversion, so both parts end up with `Nullable(Bool)` and the second block no longer checks that a part written after a metadata-only change keeps its own column types. Use `Nullable(UInt64) -> Nullable(SimpleAggregateFunction(sum, UInt64))` instead: the custom name is still nested inside `Nullable`, where `IDataType::equals` ignores it, and the ALTER stays metadata-only. Before the shared part metadata was keyed on the full type names, the two parts would share one bundle here just as they did for the `Bool` pair. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| if (command.type == AlterCommand::MODIFY_COLUMN && command.data_type) | ||
| { | ||
| const auto old_type = old_types.find(command.column_name); | ||
| if (old_type != old_types.end() && old_type->second->equals(*command.data_type) |
There was a problem hiding this comment.
[Blocker] Guard nested Bool conversions when the outer types differ
The equals prerequisite skips this protection when another component of the type changes alongside the nested UInt8 -> Bool. The updated CAST now normalizes those values, while the mutation retains an aggregate projection whose primary key does not contain the column. Queries can then return the old aggregate states instead of the converted data.
Reproduced with the PR's fast-test binary:
SET optimize_functions_to_subcolumns = 0;
CREATE TABLE t
(
id UInt32,
m Map(String, Array(UInt8)),
PROJECTION p (SELECT sum(arraySum(arrayFlatten(mapValues(m)))))
)
ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1, {'a':[2]}), (2, {'a':[255]});
ALTER TABLE t MODIFY COLUMN m Map(FixedString(1), Array(Bool))
SETTINGS mutations_sync = 2;
SELECT sum(arraySum(arrayFlatten(mapValues(m)))) FROM t
SETTINGS optimize_use_projections = 0; -- 2
SELECT sum(arraySum(arrayFlatten(mapValues(m)))) FROM t
SETTINGS optimize_use_projections = 1, force_optimize_projection = 1; -- 257Please rebuild or reject affected computed projections for these compound conversions too; requiring the complete old and new types to be equals leaves this class of stale-projection results reachable.
There was a problem hiding this comment.
Fixed in ee9e74d: the refusal now applies to every conversion that makes a Bool out of another type at some position, not only to equals pairs; 05628 checks your Map case.
There was a problem hiding this comment.
[Blocker] The stale-projection issue still reproduces at ee9e74d08261 when the conversion adds a wrapper around a composite type. In src/DataTypes/Utils.cpp:426-430, convertsToBool walks Tuple(x UInt8) -> Nullable(Tuple(x Bool)) by pairing UInt8 with Tuple(x Bool) and returns false. Consequently, the check at src/Storages/MergeTree/MergeTreeData.cpp:6924 permits the conversion while retaining the old aggregate states.
Reproduced with this commit's fast-test binary:
SET optimize_functions_to_subcolumns = 0;
CREATE TABLE t
(
id UInt32,
v Tuple(x UInt8),
PROJECTION p (SELECT sum(assumeNotNull(v).x))
)
ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1, (2)), (2, (255));
ALTER TABLE t MODIFY COLUMN v Nullable(Tuple(x Bool))
SETTINGS mutations_sync = 2;
SELECT sum(assumeNotNull(v).x) FROM t
SETTINGS optimize_use_projections = 0; -- 2
SELECT sum(assumeNotNull(v).x) FROM t
SETTINGS optimize_use_projections = 1, force_optimize_projection = 1; -- 257The same helper gap bypasses the new subcolumn-index guard: with an index on toString(assumeNotNull(v.x)), wide parts and index_granularity = 1, the completed conversion leaves WHERE toString(assumeNotNull(v.x)) = 'true' returning 0 rows with the index versus 2 without it. Please make the predicate follow CAST's independent unwrapping of Nullable/LowCardinality and cover both derived-data paths.
There was a problem hiding this comment.
Fixed in 152f13b: convertsToBool now removes Nullable and LowCardinality from each side independently, as CAST does, so Tuple(x UInt8) -> Nullable(Tuple(x Bool)) is refused under both the aggregate projection and the skip index over v.x.
There was a problem hiding this comment.
[Blocker] The claim that the guard covers every conversion still has a structural-conversion counterexample at 152f13b51e74: src/DataTypes/Utils.cpp:446-448 returns false for Array(Tuple(keys String, values UInt8)) -> Map(String, Bool) because the types have one and two direct children. FunctionCast::createMapWrapper nevertheless converts the tuple's value element to Bool, so the guard at src/Storages/MergeTree/MergeTreeData.cpp:6924 permits the alteration and retains stale aggregate states.
Reproduced with this commit's fast-test binary:
SET optimize_functions_to_subcolumns = 0;
CREATE TABLE t
(
id UInt32,
m Array(Tuple(keys String, values UInt8)),
PROJECTION p
(SELECT sum(arraySum(mapValues(CAST(m AS Map(String, UInt64))))))
)
ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1, [('a', 2)]), (2, [('a', 255)]);
ALTER TABLE t MODIFY COLUMN m Map(String, Bool)
SETTINGS mutations_sync = 2;
SELECT sum(arraySum(mapValues(CAST(m AS Map(String, UInt64))))) FROM t
SETTINGS optimize_use_projections = 0; -- 2
SELECT sum(arraySum(mapValues(CAST(m AS Map(String, UInt64))))) FROM t
SETTINGS optimize_use_projections = 1, force_optimize_projection = 1; -- 257The predicate needs to follow the supported Map/array/tuple conversions as well as wrapper removal, so different structural representations cannot bypass the derived-data protection.
There was a problem hiding this comment.
Measured: master gives the same 2 vs 257 for this ALTER, since Array(Tuple(...)) -> Map(String, Bool) already rewrites the column there, and Array(Tuple(keys String, values Int16)) -> Map(String, Int8) under the same projection gives 45 vs 301 on both. Stale projections after a rewriting conversion are the pre-existing class of #127977, so I am not widening the refusal to structural conversions here.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units25 translation units recompiled, 317 s compile time in total, 25 of them have a recent master baseline. |
…d values Now that UInt8 -> Bool rewrites the values, a version column of ReplacingMergeTree or VersionedCollapsingMergeTree must not take it: versions 2 and 1 both become 1, so FINAL and merges keep the older row of a key (ReplacingMergeTree) or collapse rows of different versions (VersionedCollapsingMergeTree). checkVersionColumnTypesConversion accepted the pair because WhichDataType sees both as UInt8; it now also refuses any conversion that convertsToBool, which covers a version that is a subcolumn too. The refusal for projections computed from the column required the old and new types to be equal, so Map(String, Array(UInt8)) -> Map(FixedString(1), Array(Bool)) still converted the column while an aggregate projection kept the raw states (2 without the projection, 257 with it; master keeps the raw bytes on both paths). It now applies to every conversion that makes a Bool out of another type at some position. convertsToBool matches the elements of named tuples by name, as CAST does, so Tuple(a UInt8) -> Tuple(a Bool, b String) is seen too. The same refusal now covers a skip index over a subcolumn of the column: the mutation rebuilds only the indices that name the column itself, so with wide parts an index on toString(p.x) kept the granules of the raw bytes and pruned every row of WHERE toString(p.x) = 'true' (0 with the index, 32 without it). A named Tuple subfield addition is metadata-only only if the retained fields and Map keys are identity conversions. With equals, Tuple(a UInt8) -> Tuple(a Bool, b String) stayed lazy under allow_metadata_only_named_tuple_alter while reads converted `a`, leaving an aggregate projection over t.a stale (2 without it, 257 with it). A value-changing conversion to another type still leaves such projections, subcolumn indices and TTL infos stale, as on master (Array(Int16) -> Array(Int8) of 300 gives 45 without the projection and 301 with it). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es in one pass `CAST` removes `LowCardinality` and `Nullable` from each side of a conversion independently, so `Tuple(x UInt8) -> Nullable(Tuple(x Bool))` converts the element `x`. `convertsToBool` paired the children of the two types instead, saw `UInt8` against `Tuple(x Bool)` and returned false, so `MODIFY COLUMN` accepted the conversion and kept an aggregate projection over `x` with the old states (`sum(assumeNotNull(v).x)`: 2 without the projection, 257 with it). It also kept a skip index over `v.x` built from the old values (0 rows with the index, 2 without; master gives the same for this conversion, because the mutation rebuilds only the indices over the column itself). Both ALTERs are now refused. The same unwrapping stops refusing `Nullable(Bool) -> Bool`, which changes no value. The named tuple branch called `tryGetPositionByName`, a linear scan, once per element, so `isIdentityConversion` was quadratic in the number of elements, and `IMergeTreeReader::performRequiredConversions` calls it for every block. It now walks the elements by position when the names agree and builds one name index otherwise. Reading a 2000-element named tuple column 30 times takes 9.10 s of user CPU before this change, 6.46 s after it and 6.78 s on master (debug build, median of 5). Co-Authored-By: Claude Opus 5.5 <[email protected]>
| } | ||
|
|
||
| if (old_type && command.data_type && !old_type->equals(*command.data_type)) | ||
| if (old_type && command.data_type && !isIdentityConversion(*old_type, *command.data_type)) |
There was a problem hiding this comment.
[Blocker] Recalculate TTL metadata when the new conversion rewrites values
The new UInt8 -> Bool mutation changes values used by TTL expressions, but this READ_COLUMN branch only adds projection/index dependencies. It adds no TTL_EXPRESSION dependency, so MutateTask retains the original ttl_infos. Whole-part expiry then deletes rows using the expiry of the old values, even when the converted values are no longer expired.
Reproduced with the fast-test binary for 152f13b51e74, using the default ttl_only_drop_parts = 0:
CREATE TABLE t (id UInt32, b UInt8)
ENGINE = MergeTree ORDER BY id
TTL if(b = 2, toDateTime('2000-01-01 00:00:00'),
toDateTime('2100-01-01 00:00:00'));
SYSTEM STOP TTL MERGES t;
INSERT INTO t VALUES (1, 2);
ALTER TABLE t MODIFY COLUMN b Bool SETTINGS mutations_sync = 2;
SELECT id, toUInt8(b) FROM t; -- 1, 1: the TTL expression now yields 2100-01-01
SELECT delete_ttl_info_max FROM system.parts
WHERE database = currentDatabase() AND table = 't' AND active;
-- 2000-01-01 00:00:00
SYSTEM START TTL MERGES t;
OPTIMIZE TABLE t FINAL;
SELECT count() FROM t; -- 0, expected 1With ttl_only_drop_parts = 1, the mutation itself deletes the row before the post-ALTER read. Please recalculate affected TTL metadata from the converted values before any expiry decision, or reject this conversion when the retained TTL metadata depends on the column. Add a regression covering whole-part expiry after the conversion.
There was a problem hiding this comment.
Not changed here: master returns the same count() = 0 for this repro, since it keeps the byte 2 and the TTL expression still gives 2000-01-01, and Int16 -> Int8 from 300 to 44 under TTL if(b = 300, ...) keeps the same stale delete_ttl_info_max and deletes the row on master too (during the mutation with ttl_only_drop_parts = 1). TTL infos left stale by a value-changing MODIFY COLUMN are the pre-existing class of #112717.
…ool-identity-conversion
ClickHouse#129731 made a CAST into `SimpleAggregateFunction(f, Bool)` (with `f` returning `Bool`) map every nonzero value to 1, as a CAST into `Bool` does, and added `isSimpleAggregateFunctionOfBool`. `convertsToBool` matched only the `Bool` custom name, so `UInt8` into such a column still counted as an identity conversion: INSERT SELECT, MODIFY COLUMN and the other gates kept the raw byte (2 stayed 2), and `WHERE CAST(v, 'Bool') = true` over a key on `toUInt8(v)` then disagreed with a full scan. `05556_cast_to_simple_aggregate_function_bool` inserted `toUInt8(2)` into `Bool` and `SimpleAggregateFunction(any, Bool)` columns and expected it to be stored as is. Both now store 1, so its correlated comparisons with the `UInt8` value 2 count 0, with and without the substitution. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The walk follows the storage type of a SimpleAggregateFunction, so a Bool in SimpleAggregateFunction(any, Tuple(x Bool)) is converted as CAST converts it; only an AggregateFunction state has no children to walk. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #130894
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
Boolcolumns (alsoSimpleAggregateFunction(f, Bool)) holding the raw byte of aUInt8source instead of converting it asCASTdoes, so a2was printed astruebut did not match= true. This affectedINSERT ... SELECT(also through materialized and refreshable views andDistributedtables), views declaringBoolover aUInt8column,ALTER TABLE ... MODIFY COLUMNfromUInt8toBoolonMergeTreetables, which now rewrites the column likeUInt8toEnum8and is refused for sorting key, partition key and version columns and for columns a projection computes from or a skip index reads a subcolumn of, andATTACH/REPLACE/MOVE PARTITIONfrom aUInt8column into aBoolone, which is now refused likeInt8. Closes #130894.Description
On 26.10.2.103,
INSERT INTO users SELECT id, active FROM legacywithlegacy.active UInt8 = 2andusers.active Boolstores the byte 2: it printstrue, butcountIf(active = true)does not count it.IDataType::equalscompares the representation, soBoolequalsUInt8at every nesting level, and every gate that skips a conversion onequalslets the byte through (makeConvertingActions, the metadata-onlyALTERand its part reader,ATTACH PARTITION).The fix adds
isIdentityConversion(from, to)toDataTypes/Utils(equals, and no position wheretohasBool, or aSimpleAggregateFunction(f, Bool)whosefreturnsBool, andfromdoes not) and uses it at those gates, the mutation and skip-index gates, the lazy namedTupleALTER, view inlining,Merge/MVPREWHEREeligibility, nestedCAST, and theDistributedinsert path. The mutation keeps projections computed from the column and skip-index granules over its subcolumns, so those refuse theALTER, as do version columns, whose versions would collapse to 1.equalsis unchanged: header checks andgetLeastSupertyperely on it.Not changed: the
equalsshortcuts ofcastColumn(Distributedreads,Buffer,MemoryafterALTER) andconvertFieldToType(theVALUESexpression fallback), query-time common types (if,UNION ALL,JOIN ... USING), format type hints, the native protocol,AggregateFunctionstates,JSONtyped paths andVariantalternatives (#129664 changes the sameprepareImplline). On a replicated table, run theMODIFY COLUMNonce all replicas are upgraded: an older one keeps the raw bytes.Validation: the new
05628_uint8_to_bool_conversionfails on master and passes with the fix (50/50 randomized); the updated04870/04871/05556fail on master. A/B sweep of related tests: no new failure.Workflow [PR]
Sync PR [sync-upstream/pr/131433]