Skip to content

Fix an element added to a named Tuple getting 0 instead of the default of its type - #131186

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:named-tuple-new-element-type-default
Nov 13, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:named-tuple-new-element-type-default

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #130899
Related: #131124
Related: #130259
Related: #130898

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 an element added to a named Tuple by ALTER TABLE ... MODIFY COLUMN, INSERT ... SELECT or CAST getting 0 in existing rows instead of the default of its type. For an Enum whose first value is not 0 this is the wrong value, and often not a value of the Enum at all: after such an ALTER, SELECT * failed with UNKNOWN_ELEMENT_OF_ENUM.

Description

On 26.10.2.103 (also 26.8.21.12), ALTER TABLE t MODIFY COLUMN attrs Tuple(a UInt8, status Enum8('x' = 1, 'y' = 2)) on a table with attrs Tuple(a UInt8) stores 0 in attrs.status of existing rows, which is not a value of the Enum: SELECT * FROM t then throws UNKNOWN_ELEMENT_OF_ENUM while CHECK TABLE passes. INSERT ... SELECT from the narrower Tuple, CAST, Array(Tuple(...)) and Map(K, Tuple(...)) columns, the Memory engine and the metadata-only ALTER (allow_metadata_only_named_tuple_alter = 1, old parts converted on read and on merge) do the same. With Enum8('m' = -3, 'n' = 0, 'o' = 4) the new element is n instead of m.

FunctionCast::createTupleWrapper matches the elements of named tuples by name and filled a target element without a source with createColumn()->cloneResized(n), the column zero, bypassing IDataType::insertDefaultInto, which gives an Enum (or a Tuple or typed JSON path containing one) its type default. All the paths above convert through it. Such an element is now filled with insertManyDefaultsInto when the default insertion of its type is not trivial; other types keep cloneResized.

ALTER TABLE ... ADD COLUMN was already correct. Values stored by earlier mutations are not rewritten (ALTER TABLE ... UPDATE repairs them).

The new test covers CAST, the mutation with Array/Map, the metadata-only ALTER, INSERT ... SELECT and Memory. It fails on master and passes with the fix.

The cause was first found by @ Marouane-elfadli in #131124. My #130259 changes the same line inside a larger rework of the format readers and will take this version.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2199-master (included in 26.11 and later)

`FunctionCast::createTupleWrapper` matches the elements of named tuples
by name. A target element without a source element was filled with
`createColumn()->cloneResized(n)`, which appends the column zero and
bypasses `IDataType::insertDefaultInto`, the place where an `Enum` gets
its first value (and a `Tuple` or a typed `JSON` path containing one gets
the same). So `CAST`, `ALTER TABLE ... MODIFY COLUMN` (the mutation, and
the reads and merges of old parts after a metadata-only ALTER with
`allow_metadata_only_named_tuple_alter = 1`), `INSERT ... SELECT` from the
narrower tuple and `Memory` tables gave the new `Enum` element 0, which
is either not a value of the `Enum` (the ALTER then stored it and
`SELECT *` threw UNKNOWN_ELEMENT_OF_ENUM) or not its default.

For a type whose default insertion is not trivial the element is now
filled with `insertManyDefaultsInto`, as the hash join does for the key
of a not-matched row. Trivial types keep `cloneResized`: it is one
resize, and `Nothing` (trivial) has no `insertDefaultInto`.

Closes ClickHouse#130899

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; 1 finding) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test does not assert that the MODIFY COLUMN mutation and the OPTIMIZE FINAL merge after the metadata-only ALTER actually ran (05628_...sql) DISAGREE With allow_metadata_only_named_tuple_alter = 0 the ALTER always requires a mutation (AlterCommands.cpp, isTrueMetadataOnlyConversion does not unwrap Tuple, no lazy setting applies) and mutations_sync = 2 waits for it; OPTIMIZE FINAL waits for running merges and merges the two parts. Read-time conversion uses the same createTupleWrapper, so the test fails on master on every path.
2 💡 A new element of a type that holds both a bare Nothing and an Enum, e.g. CAST(... AS Tuple(a UInt8, t Tuple(n Nothing, e Enum8('x' = 1)))), now throws NOT_IMPLEMENTED (Nothing has no default) instead of returning 0 for the Enum noted, not blocking Such a type cannot be a table column, so only a hand-written CAST reaches it; a top-level Nothing element still works.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT toInt8(CAST(tuple(5)::Tuple(a UInt8) AS Tuple(a UInt8, status Enum8('x' = 1, 'y' = 2))).status) prints 0 on master on every run; the MODIFY COLUMN mutation, metadata-only ALTER, INSERT ... SELECT and Memory cases give 0 too, and SELECT * throws UNKNOWN_ELEMENT_OF_ENUM. Same on official 26.8.21.12 and 26.10.2.103.
b Root cause explained? FunctionCast::createTupleWrapper filled a target element without a source with createColumn()->cloneResized(n), the column zero, bypassing IDataType::insertDefaultInto, which gives an Enum its first value. Every listed path converts through this wrapper.
c Fix matches root cause? Yes. The fill goes through insertManyDefaultsInto when the type's default insertion is not trivial; other types keep cloneResized. No guard at a read site.
d Test intent preserved / new tests added? New test 05628_named_tuple_new_element_type_default covers every path from the issue, including allow_metadata_only_named_tuple_alter = 1. No existing test changed.
e Both directions demonstrated? Master: the test fails with UNKNOWN_ELEMENT_OF_ENUM. Fix: 50/50 randomized runs pass, and the output is identical with forced Wide and Compact parts.
f Fix is general across code paths? One fill site serves CAST, the mutation, metadata-only reads and merges, INSERT ... SELECT, Memory and ReplicatedMergeTree (checked locally). Positional tuple conversion has no unmatched element.
g Fix generalizes across inputs (params/datatypes/wrappers)? Enum8, Enum16, an Enum whose 0 is not the first value, an Enum inside a new Tuple, an element added inside a nested Tuple, a typed JSON path, Array(Tuple), Map(K, Tuple) and accurateCastOrNull are covered. Nullable, LowCardinality, Array, Map, Variant, String and top-level Nothing elements are unchanged.
h Backward compatible? (maintainer-approved exception only) Yes. No setting is needed: the old value was not a valid value of the Enum (or not its default). Values stored by earlier mutations are not rewritten.
i Invariants and contracts preserved? Both branches return a full column of the element type with exactly input_rows_count rows. The accurateCastOrNull null-map pass that follows is unchanged.

Session id: cron:clickhouse-impl-slot-7:20261113-021600

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9acd7ef]

Summary: ✅


AI Review

Summary

Reviewed #131186 at 9acd7ef4887210d79fe54feb0a4c4cc50cafa1b5, including all prior discussion. The change fills missing named Tuple elements with their type defaults, preventing invalid zero values in added Enum elements. No actionable findings. The focused regression test covers casts, nested types, mutations, metadata-only reads and merges, inserts, and Memory; it passed in the PR's Fast test report.

Final Verdict

Status: ✅ Approve.

@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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9acd7ef48 with master acd88ab8f (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.56, programs/clickhouse-keeper ×0.61 (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 _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.1 s +5.1 s (+253%)
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.3 s 8.6 s +5.0 s (+141%)
Compile time of recompiled translation units

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

Job report

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 2dd7ee4 Nov 13, 2026
604 of 608 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants