Skip to content

Fix Bool columns storing values other than 0 and 1 written from a UInt8 source - #131433

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/uint8-to-bool-identity-conversion
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/uint8-to-bool-identity-conversion

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #130894

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed Bool columns (also SimpleAggregateFunction(f, Bool)) holding the raw byte of a UInt8 source instead of converting it as CAST does, so a 2 was printed as true but did not match = true. This affected INSERT ... SELECT (also through materialized and refreshable views and Distributed tables), views declaring Bool over a UInt8 column, ALTER TABLE ... MODIFY COLUMN from UInt8 to Bool on MergeTree tables, which now rewrites the column like UInt8 to Enum8 and 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, and ATTACH/REPLACE/MOVE PARTITION from a UInt8 column into a Bool one, which is now refused like Int8. Closes #130894.

Description

On 26.10.2.103, INSERT INTO users SELECT id, active FROM legacy with legacy.active UInt8 = 2 and users.active Bool stores the byte 2: it prints true, but countIf(active = true) does not count it.

IDataType::equals compares the representation, so Bool equals UInt8 at every nesting level, and every gate that skips a conversion on equals lets the byte through (makeConvertingActions, the metadata-only ALTER and its part reader, ATTACH PARTITION).

The fix adds isIdentityConversion(from, to) to DataTypes/Utils (equals, and no position where to has Bool, or a SimpleAggregateFunction(f, Bool) whose f returns Bool, and from does not) and uses it at those gates, the mutation and skip-index gates, the lazy named Tuple ALTER, view inlining, Merge/MV PREWHERE eligibility, nested CAST, and the Distributed insert path. The mutation keeps projections computed from the column and skip-index granules over its subcolumns, so those refuse the ALTER, as do version columns, whose versions would collapse to 1. equals is unchanged: header checks and getLeastSupertype rely on it.

Not changed: the equals shortcuts of castColumn (Distributed reads, Buffer, Memory after ALTER) and convertFieldToType (the VALUES expression fallback), query-time common types (if, UNION ALL, JOIN ... USING), format type hints, the native protocol, AggregateFunction states, JSON typed paths and Variant alternatives (#129664 changes the same prepareImpl line). On a replicated table, run the MODIFY COLUMN once all replicas are upgraded: an older one keeps the raw bytes.

Validation: the new 05628_uint8_to_bool_conversion fails on master and passes with the fix (50/50 randomized); the updated 04870/04871/05556 fail on master. A/B sweep of related tests: no new failure.


Workflow [PR]
Sync PR [sync-upstream/pr/131433]

groeneai and others added 2 commits November 13, 2026 20:35
`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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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.

# Sev Finding Verdict Evidence / action
1 ❌ The Distributed INSERT block of 05628 would log Structure does not match ... to the client's stderr with async inserts off (the CI default) DISAGREE the client runs a file that has error hints at send_logs_level = 'fatal' (ClientBase::executeMultiQuery), and 05628 has six; measured with async_insert = 0: the block alone fails on stderr, with one hint it passes; 05628 50/50 randomized
2 ❌ if, UNION ALL and JOIN ... USING over Bool and UInt8 still return a Bool holding 2 DISAGREE the label comes from getLeastSupertype at query time (the first of two equals types); the INSERT that follows is Bool -> Bool. Separate PR; casting USING keys first would undo #129894. Listed under "Not changed"
3 ❌ INSERT ... VALUES (2::UInt8) with input_format_values_deduce_templates_of_expressions = 0 still stores 2 DISAGREE that fallback converts through convertFieldToType, whose equals shortcut also serves skip-index, statistics and Iceberg pruning; separate PR. The default VALUES path wraps the value in _CAST and converts. Listed under "Not changed"
4 ❌ ALTER ... MODIFY COLUMN of a Memory table from UInt8 to Bool still reads 2 DISAGREE Memory converts on read through castColumn, kept whole like Distributed reads and Buffer; the changelog now says MergeTree, and Memory is listed under "Not changed"
5 ❌ Bool -> UInt8 stays metadata-only, so a key expression such as toString(b) keeps a stale primary index DISAGREE unchanged from master (Bool -> UInt8 is an identity there and here, and the data stays valid); the same holds for every metadata-only ALTER that changes a key expression's value (Enum8 -> Int8, DateTime -> UInt32). Separate defect
6 ❌ Variant(Array(UInt8), String) to Variant(Array(Bool), String) now builds a CAST that the Variant wrapper refuses by alternative name, so INSERT SELECT throws and an old part ALTERed between them would not read AGREE, fixed Variant alternatives are left as is, like JSON typed paths; guard test added; listed under "Not changed"
13 ❌ After MODIFY COLUMN from UInt8 to Bool, an aggregate projection such as sum(active) keeps its states over the raw bytes (257 against 2 from the parent part) AGREE, fixed the state type does not change, so neither the projection check of the ALTER nor the mutation sees it; the ALTER is now refused when an aggregate projection aggregates the column, as it already is for conversions that change the state type (Int16 -> Int8); test added
14 ❌ The same mutation does not recompute MATERIALIZED columns computed from the column DISAGREE the mutation recomputes them only for UPDATE, patches and CLEAR (MutationsInterpreter::prepare), so every rewriting MODIFY COLUMN (Int16 -> Int8) leaves them as written on master; separate behaviour change
15 ❌ The ALTER refusal misses an aggregate projection over a subcolumn of the column (sum(t.x), m.values), which keeps raw states (258 against 3) AGREE, fixed the projection's required columns are resolved to their storage column, as the key checks of the same function do; test added
20 ❌ A normal projection with WHERE active = 1 is not rebuilt by the mutation, so a query through it misses the rows whose 2 became true (1 [1] against 2 [1,2]) AGREE, fixed the refusal now covers every projection the mutation does not rebuild and that computes from the column: aggregate states, WHERE, a sorting key over an expression or subcolumn of it; a normal projection storing the column as is stays accepted and is converted on read; tests added for each
21 ❌ Two-level aggregation over a Distributed table declaring Bool over UInt8 can return several true groups when the local plan converts after the shards aggregated DISAGREE master returns the same groups (raw 1, 2, 255, each printed true); Distributed reads are listed under "Not changed", and the prescribed change to conversionPreservesOrder is exactly the open #131028 (closes #130889)
16 ❌ ORDER BY ... LIMIT pushed into a view declaring Bool over UInt8 sorts the raw bytes before the view converts them, so it keeps the wrong row AGREE, fixed the pushdown now requires an identity conversion, like view inlining; test added
23 ⚠️ A normal projection carrying its own minmax index on the column (WITH SETTINGS (add_minmax_index_for_numeric_columns = 1)) is accepted, but its hardlinked index granules keep the raw bytes, so a read through it can skip rows that now hold true DISAGREE measured: the per-part skip-index type check (MergeTreeIndices.cpp, now through isIdentityConversion) does not use that index on the hardlinked UInt8 projection part under Bool metadata (EXPLAIN: 2/2 granules, master 1/2); reads through the forced projection and without it return the same rows
7 ⚠️ A named-tuple field addition under allow_metadata_only_named_tuple_alter keeps a UInt8 -> Bool element change metadata-only DISAGREE a lazy conversion by design; the tuple types are not equals, so every read goes through _CAST and converts the element
8 ⚠️ No automated test reaches the compressed fast path of writeRemoteConvert DISAGREE no stateless cluster is compressed; checked locally on a compressed cluster: master 2, the fix 1, the fix without that hunk 2
9 ⚠️ The partition-key refusal is not tested AGREE (as a nit), fixed test line added; the refusal is the existing partition-key check in the same branch as the sorting-key one
17 ⚠️ DROP PROJECTION p, MODIFY COLUMN ... in one ALTER is refused although p is gone afterwards AGREE, fixed projections the ALTER drops are skipped, as the Int16 -> Int8 refusal in AlterCommands::apply does; test added
18 ⚠️ The key-projection control does not read through the projection AGREE, fixed the query forces the projection
10 💡 04870 header still said no case creates a mutation AGREE, fixed header updated
11 💡 PR body: an unmeasured repair recipe, the overlap with #129664 AGREE, fixed recipe removed, overlap stated
12 💡 The isIdentityConversion comment does not mention the JSON exception AGREE, fixed comment names JSON and Variant
19 💡 The isIdentityConversion comment does not mention aggregate-state arguments AGREE, fixed comment names AggregateFunction and SimpleAggregateFunction
22 💡 The tests do not assert a converted value inside Tuple, Map or LowCardinality AGREE (narrowed), fixed INSERT ... SELECT into Tuple(x Bool) and Map(String, Bool) added; LowCardinality(Bool) needs allow_suspicious_low_cardinality_types and was checked locally only
24 💡 The 04871 case 19 comment says Tuple(x Bool) and Tuple(x UInt8) share one interned entry AGREE, fixed the entries are keyed on the type name; the comment now says the types are equals
25 💡 While the mutation is pending, a projection keyed on the column still has its old primary index DISAGREE projection analysis skips pending RENAME/DROP only (partHasPendingMetadataMutationsOnColumns), for every type-changing MODIFY COLUMN of a projection key column on master; separate PR

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261113-204000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's INSERT ... SELECT, MODIFY COLUMN and ATTACH PARTITION FROM repro stores 2 and 255 in a Bool column on every run on master (also on 26.10.2.103 and 26.8.18.2); the new test fails on master with and without randomization.
b Root cause explained? IDataType::equals compares the representation, so Bool equals UInt8 at every nesting level. The gates that skip a conversion on equals (makeConvertingActions, isTrueMetadataOnlyConversion, the part-read conversion, the partition structure check, the Distributed insert path) therefore let raw bytes reach a Bool column.
c Fix matches root cause? Yes. One predicate, isIdentityConversion, replaces equals at those gates; the conversion itself is the existing one (CAST, the part reader, the mutation, INCOMPATIBLE_COLUMNS). equals is unchanged because header checks and getLeastSupertype rely on it.
d Test intent preserved / new tests added? New 05628_uint8_to_bool_conversion (every block fails on master). 04870 case 17 and 04871 case 19 are updated for the new behaviour and fail on master; 04871 still tests the stale skip index of a subcolumn by attaching in the direction that is still allowed.
e Both directions demonstrated? Yes: all three tests fail on master and pass with the fix. The compressed async Distributed send was checked with three binaries: master stores 2, the fix 1, the fix without the writeRemoteConvert change 2.
f Fix is general across code paths? Every equals/structure gate in front of makeConvertingActions, CAST or MergeTree's ALTER, part-read, skip-index and partition logic, incl. MV, refreshable MV, views (also the ORDER BY ... LIMIT pushdown into a view), Merge and Distributed inserts. Distributed reads and Buffer convert through castColumn's own shortcut and are left as on master, so a read does not depend on prefer_localhost_replica.
g Fix generalizes across inputs (params/datatypes/wrappers)? Scalar, constant, Nullable (incl. NULL), Array, Tuple, Map and LowCardinality positions all convert on INSERT and MODIFY COLUMN. JSON typed paths, Variant alternatives (CAST matches them by name), AggregateFunction(f, Bool) states and SimpleAggregateFunction(f, Bool) are left as they are on purpose.
h Backward compatible? (maintainer-approved exception only) No setting or format change. Behaviour changes follow CAST: MODIFY COLUMN UInt8 -> Bool is a mutation and is refused on key columns, like UInt8 -> Enum8, and on a column a projection aggregates, filters by or sorts by through an expression or a subcolumn such as t.x, unless the projection is keyed on the column itself (the mutation keeps the parts of a projection it does not rebuild; for an aggregate state Int16 -> Int8 is refused there by CANNOT_CONVERT_TYPE), while a projection that stores the column as is converts it on read; ATTACH/REPLACE/MOVE PARTITION from UInt8 into Bool is refused, like Int8. Bool -> UInt8 stays metadata-only.
i Invariants and contracts preserved? The predicate is pure and allocation-free; each gate keeps its branch structure and takes the branch it already takes for any other differing type, so converted headers come from makeConvertingActions as before. 05628 passes 50/50 randomized runs, and the three tests pass with and without randomization; A/B runs of 1205 Distributed-insert, refreshable-view, variant, projection and view tests, and of the 369 projection tests after the last refusal change, show no new failure. A projection's own skip index over the column is not used on its not-yet-rebuilt part (per-part type check), so reads through it match plain reads.

Session id: cron:clickhouse-impl-slot-6:20261113-202300

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0a7cad0]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR makes UInt8-to-Bool writes and MergeTree type changes normalize nonzero values, and rejects incompatible partition transfers. Reviewed PR head 0a7cad010ec8179a5c9b69458792678001300457 in merge commit 1facc0f4eef5cbef8b653cca5eb2f556309a6ebf, including the prior discussion and CI results. Two previously dismissed correctness findings remain reproducible. The earlier Merge read-order finding no longer reproduces in the current code, and its thread was resolved. No new inline findings were posted.

Findings

❌ Blockers

Tests
  • ⚠️ Add a focused regression comparing an aggregate with projections disabled and forced after a structural conversion containing UInt8 to Bool.
  • ⚠️ Add a regression verifying that a row whose TTL moves into the future survives the conversion and subsequent TTL processing.

Both failures were reproduced using the PR's CI fast-test binary, which reports the reviewed merge commit as GIT_HASH. Existing CI reports no failed tests. Reproduction SQL and logs are under tmp/review_131433/.

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.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-data-types Type system & core datatypes used across query planning/execution. labels Nov 13, 2026
`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]>
Comment thread src/Storages/AlterCommands.cpp Resolved
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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; -- 257

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

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.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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; -- 257

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

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.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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; -- 257

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

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bd30ca7a4 with master 2b1bef1d3 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.68, programs/clickhouse-keeper ×0.68 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.5 s 14.3 s +9.9 s (+225%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.8 s +5.3 s (+216%)
Compile time of recompiled translation units

25 translation units recompiled, 317 s compile time in total, 25 of them have a recent master baseline.

Job report

…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]>
Comment thread src/DataTypes/Utils.cpp Resolved
…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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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 1

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

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.

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.

Comment thread src/Interpreters/ActionsDAG.cpp Resolved
groeneai and others added 3 commits November 17, 2026 17:43
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]>

This branch has not been deployed

No deployments
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 comp-data-types Type system & core datatypes used across query planning/execution. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

1 participant