Skip to content

Fix an explicit NULL storing 0 in an Enum column with input_format_null_as_default - #131190

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:null-as-default-type-default
Nov 13, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:null-as-default-type-default

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #118515
Related: #130975

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 explicit NULL read into a non-Nullable column with input_format_null_as_default storing the zero of the column instead of the default of its type in the text formats and BSONEachRow. An Enum without a 0 element got 0, after which every SELECT of the table failed with UNKNOWN_ELEMENT_OF_ENUM; INSERT ... VALUES (NULL) already stored the default.

Description

On 26.8.2.3, INSERT INTO t FORMAT JSONEachRow {"e": null} into an Enum8('a' = 1, 'b' = 2) column stores 0 with the default input_format_null_as_default = 1, and then SELECT * FROM t fails with UNKNOWN_ELEMENT_OF_ENUM. The same happens for \N in CSV, TSV, TSKV, CustomSeparated, Regexp and MySQLDump, for a BSON null, and for a Tuple or JSON holding an Enum (also through Values). An Enum whose 0 is a member but not the first one silently got the wrong value.

Root cause: the SerializationNullable::deserializeNullAsDefaultOrNested* helpers only receive the nested serialization, so on a null they insert IColumn::insertDefault(), the column zero. AddingDefaultsTransform only replaces columns that have a DEFAULT expression, so for all other columns the zero is final. BSONEachRowRowInputFormat::readField had the same call.

Change: the helpers take the type and insert IDataType::insertDefaultInto when isDefaultInsertTrivial() is false, keeping insertDefault() otherwise, so trivial types, Nothing and the Nullable paths are unchanged. Every top-level caller passes the type it already has; BSON uses the same check, which also covers its array, tuple and map elements. A whole-value null for Tuple(Nothing, Enum8(...)) in format() now fails with NOT_IMPLEMENTED, as it does when that column is missing.

Not covered: a null element inside a text-format Array/Map/Tuple value, and the Avro, MsgPack and columnar readers.

Validation: the new test fails on master and passes with the fix (50/50 randomized runs, ASan clean); 236 existing format, null_as_default and Enum tests give identical results on both binaries. Over 10M all-null TSV rows, trivial types stay within noise and an all-Enum file is 4.7% slower single-threaded, since it now writes the real default.


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

Version info

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

…ull_as_default

With `input_format_null_as_default = 1` (the default), an explicit null for a
non-`Nullable` column is read by the `SerializationNullable::deserializeNullAsDefaultOrNested*`
helpers. Their shared core `deserializeImpl` handled a detected null with
`IColumn::insertDefault()`, the zero of the column, because the helpers only
received the nested serialization, never the type. For `Enum` the type default is
the first element, and 0 may not be a member at all, so
`INSERT INTO t FORMAT JSONEachRow {"e": null}` into an `Enum8('a' = 1, 'b' = 2)`
column stored 0 and every later `SELECT` of the table failed with
`UNKNOWN_ELEMENT_OF_ENUM`. A `Tuple` or `JSON` type holding an `Enum` had the same
problem. `AddingDefaultsTransform` only replaces columns with a `DEFAULT`
expression, so for every other column the zero was final.

The six non-`try` helpers now take the type and `deserializeImpl` inserts
`IDataType::insertDefaultInto` when the type's default is not trivial; for every
type whose default IS the column zero the statement is unchanged (this also keeps
a top-level `Nothing` null accepted, since `Nothing::insertDefaultInto` throws).
All top-level callers pass the type they already have in scope (JSON*, CSV, TSV,
TSKV, CustomSeparated/Template/Regexp/Freeform through the escaping rules,
MySQLDump, Values, GeoJSON). `BSONEachRowRowInputFormat::readField` had the same
`insertDefault()` on a BSON null; it now uses the same guarded call, which also
covers BSON array, tuple and map elements because `readField` recurses with the
element type. The `Nullable` paths pass no type and are unchanged.

Nested elements of text-format `Array`/`Map`/`Tuple` values still insert the
column zero: those serializations hold no element types.

Closes ClickHouse#118515

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; 0 findings) plus my own cold review (2 nits, no code change).

# Sev Finding Verdict Evidence / action
1 💡 The issue also lists null elements inside text-format Array/Map/Tuple values, which this PR does not change DISAGREE (keep Closes) The issue's title, reproducer and expected output are top-level and covered by the new test; the nested case is named under "Not covered" in the description

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

Session id: cron:clickhouse-review-self-slot-58:20261113-040200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. format(JSONEachRow, 'e Enum8(''a'' = 1, ''b'' = 2)', '{"e":null}') returns 0 on master every time; the same for CSV/TSV \N, BSON null and Values (NULL) into a Tuple holding an Enum. On 26.8.2.3 an INSERT ... FORMAT JSONEachRow {"e": null} into MergeTree makes SELECT * fail with UNKNOWN_ELEMENT_OF_ENUM.
b Root cause explained? The deserializeNullAsDefaultOrNested* helpers only get the nested serialization, so on a null they insert IColumn::insertDefault() (the column zero, out of the Enum domain); AddingDefaultsTransform only replaces columns with a DEFAULT expression. BSONEachRowRowInputFormat::readField had the same call.
c Fix matches root cause? Yes. The helpers take the type and insert IDataType::insertDefaultInto where the null is detected, which is the helper's documented contract; no per-caller patching.
d Test intent preserved / new tests added? New 05628_null_as_default_uses_type_default: every helper kind, the in-buffer and end-of-input null checks, Tuple, an Enum with 0 as a non-first member, BSON top level and array element, a DEFAULT column, input_format_defaults_for_omitted_fields = 0, and Nothing. No existing test changed.
e Both directions demonstrated? Master binary: the test fails with Code: 691. Fixed binary: passes, 50/50 randomized runs (parallel parsing on and off, many buffer sizes).
f Fix is general across code paths? All 16 top-level callers pass the type (JSON*, CSV, TSV, TSKV, CustomSeparated/Template/Regexp/Freeform, MySQLDump, Values, GeoJSON); BSON fixed at the recursive readField, so its elements too. Not covered: null elements inside text-format Array/Map/Tuple values (no element types there) and the Avro/MsgPack/columnar readers.
g Fix generalizes across inputs (params/datatypes/wrappers)? Enum8/Enum16, Tuple, nested Tuple, JSON typed path, sparse columns, custom null representations, CSV bad-values mode, end of input. Trivial types, Nothing, Array, Map, Variant, Nullable, LowCardinality(Nullable) keep the old statement (measured unchanged).
h Backward compatible? (maintainer-approved exception only) No setting or format change; an explicit null now stores the default as INSERT ... VALUES (NULL) and a missing field already did; stored data is unchanged. The one new error is a whole-value null for Tuple(Nothing, Enum8(...)) in format(), matching the missing-column case.
i Invariants and contracts preserved? Exactly one value is inserted per row on every path (DataTypeTuple/DataTypeObject roll back partial inserts on exception); the null branch reads nothing more; the helper still returns false for a null, so DEFAULT expressions still apply; the Nullable path is unchanged. ASan clean.

Session id: cron:clickhouse-impl-self-slot-57:20261113-025400

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ecb16d9]

Summary: ✅


AI Review

Summary

Reviewed #131190 at ecb16d9824bbc9e3b132afa80ed352be8609fee2, including all prior discussion, the complete diff, and the affected parsing and default-insertion paths. The change makes explicit nulls use the type default for non-Nullable columns in the covered text formats and BSONEachRow, preventing out-of-domain Enum values while preserving column DEFAULT expressions. No actionable findings. Nested text-format null elements are explicitly outside this change and remain documented in the linked #118515.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build was available for independent execution. The new 05628_null_as_default_uses_type_default regression passed in Fast test. Dedicated bugfix-validation and sanitizer results were not complete at review time; their completed CI reports would close this verification gap.
Final Verdict

Status: ✅ Approve. No changes requested and no new inline findings posted.

@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-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ecb16d982 with master 365bb22b2 (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.61, 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&) 5.5 s 11.2 s +7.9 s (+232%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.3 s 7.3 s +5.3 s (+260%)
Compile time of recompiled translation units

30 translation units recompiled, 116 s compile time in total, 30 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 3a137cc Nov 13, 2026
604 of 608 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
cwurm pushed a commit to cwurm/ClickHouse that referenced this pull request Nov 13, 2026
…l_as_default

With input_format_null_as_default = 1, an Avro null (a union(null, X)
value or a field of Avro type null) or a MsgPack nil read into a
non-Nullable column appended IColumn::insertDefault(), the zero of the
column, and reported the value as missing. Only AddingDefaultsTransform
consumes that bit, and only for columns with a DEFAULT expression, so for
every other column the zero was final. For Enum the zero is outside the
domain (or a member that is not the first one): the stored value is wrong
and SELECT of a table holding it fails with UNKNOWN_ELEMENT_OF_ENUM. A
Tuple or JSON holding an Enum had the same problem.

Insert IDataType::insertDefaultInto when the type's default is not
trivial, as ValuesBlockInputFormat and the JSONEachRow/BSON missing-field
paths already do. The isDefaultInsertTrivial() guard keeps the old
statement for every other type; it matters for Nothing, whose
insertDefaultInto throws while a Nothing null is accepted today. The
missing bit is unchanged, so a DEFAULT expression still takes precedence.
Array elements, Map keys/values and record fields go through the same
statements because both readers recurse with the element type.

The text formats and BSONEachRow get the same rule in ClickHouse#131190. The
columnar readers (Native, Parquet, Arrow, ORC) lose the default through a
different mechanism and are not changed here.

Related: ClickHouse#118515

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim pushed a commit to raimannma/ClickHouse that referenced this pull request Nov 17, 2026
With `input_format_null_as_default` (the default) a NULL element of an
`Array`, a `Tuple` or a `Map` key or value whose type is a non-Nullable
`Enum` was stored as the column zero. 0 is not a member of e.g.
`Enum8('a' = 1, 'b' = 2)`, so the part was written and every later read of
the column failed with UNKNOWN_ELEMENT_OF_ENUM. The same happened for an
empty string element with `input_format_json_empty_as_default`.

Since ClickHouse#131190 / ClickHouse#131198 the `SerializationNullable::deserializeNullAsDefaultOrNested*`
and `JSONUtils::deserializeEmpyStringAsDefaultOrNested` helpers insert
`IDataType::insertDefaultInto` when they are given the type, and every
top-level reader passes it. The element readers of the composite
serializations did not: `SerializationArray` and `SerializationMap` held no
element type, `SerializationTuple` held `elem_types` (ClickHouse#131189) without
passing them, and the `tryDeserializeNullAsDefaultOrNested*` helpers had no
type parameter at all (used by every `tryDeserialize*` of a composite, e.g.
`Variant` text parsing).

`SerializationArray` now holds its element type and `SerializationMap` its
key and value types (mandatory in `create`, so a missed caller does not
compile); `SerializationArray::SubcolumnCreator` passes `prev_type`. The six
`try` helpers take the same trailing `nested_type` as the throwing ones, and
all 21 nested call sites (text, JSON, CSV, CSV split tuple columns, and the
JSON "" path) pass the element type.

The types are deliberately not part of the pool keys: hashing an Enum type
per serialization request was measured 51.9x slower on
`system.metric_log`'s `Map(Enum16(...), Int64)` in ClickHouse#131189. A pooled
serialization keeps the first creator's type, which is correct because
equal element serialization keys imply equal defaults: only `Enum`
(whose key hashes every value), `Tuple` (recursive key) and `JSON`
(never pooled) have a non-trivial default.

Closes ClickHouse#132007

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). 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

Development

Successfully merging this pull request may close these issues.

null_as_default writes out-of-domain Enum 0 in JSONEachRow/CSV/TSV (Values is correct)

3 participants