Skip to content

Use the type default for values missing from Native and JSON input - #131189

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-missing-values-type-default
Nov 13, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-missing-values-type-default

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #130898
Related: #130259
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):

A column missing from Native or JSONColumns input, and an element of a named Tuple missing from a JSON object, get the default of their type instead of the zero of the column: an Enum without a 0 member stored an invalid value, and every later read of the table failed with UNKNOWN_ELEMENT_OF_ENUM.

Description

On 26.10.2.103 (also 26.8.21.12 and 26.3.33.24), INSERT INTO t SELECT * FROM file('old.native') into a table whose status Enum8('a' = 1, 'b' = 2) column the file lacks stores 0, and every later SELECT * FROM t fails with UNKNOWN_ELEMENT_OF_ENUM. JSONColumns input without the column and a JSON object without a named Tuple element store the same 0; for Enum8('m' = -3, 'n' = 0, 'o' = 4) they silently store 'n' instead of the default 'm'.

NativeReader::read, JSONColumnsBlockInputFormatBase::read and SerializationTuple::deserializeTupleJSONImpl filled the absent value through the column API (cloneResized, insertManyDefaults, insertDefault), which knows only the column zero; only IDataType::insertDefaultInto knows the type default.

When isDefaultInsertTrivial() is false, the three sites now use insertManyDefaultsInto / insertDefaultInto, the branch HashJoinResult.cpp already uses; every other type keeps its current code path, and a missing Nothing element is still accepted. SerializationTuple now holds its element types for these defaults; they are not part of its pool key, because the element serializations already determine the defaults.

New test 05628 fails on master with Code: 691 and passes with the fix (50 randomized runs, ASan).

Not covered here: Parquet, ORC, Arrow and Vortex (#130259), CSV, TSV and *WithNames formats (#130975); the JSON type, JSONExtract, Avro with input_format_avro_allow_missing_fields, Protobuf, VALUES (..., DEFAULT), RowBinaryWithDefaults and JSON empty_as_default still store the zero.


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

Version info

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

A column missing from a Native block or from a JSONColumns object, and an
element of a named Tuple missing from a JSON object, were filled with the
column zero (`cloneResized`, `insertManyDefaults`, `insertDefault`). For an
`Enum` whose members do not include 0 that stores a value outside the type,
and every later text read of the table fails with UNKNOWN_ELEMENT_OF_ENUM;
for an Enum that has 0 as a non-first member it silently stores the wrong
member. Only `IDataType::insertDefaultInto` knows the type default.

Take the type default at the three sites when it is not the column zero
(`isDefaultInsertTrivial`), the same branch the hash join uses
(`HashJoinResult.cpp`); trivial types keep their current code path, and a
missing `Nothing` element is still accepted. `SerializationTuple` only held
element serializations, so it now also holds the element types, used only
for these defaults. They are not part of its pool key: the key of each
element serialization already determines the default of its type (`Enum`
hashes its values, a `JSON` element is never pooled), and hashing the types
would hash the whole declaration of a large `Enum` on every serialization
request (the `Map(Enum16, Int64)` of `system.metric_log`).

Related: ClickHouse#130898
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, head e382c90)
Finding Verdict
❌ Hashing the element types into the SerializationTuple pool key re-hashed the whole declaration of a large Enum on every serialization request (Map(Enum16, Int64) of system.metric_log: 0.65 us -> 33.9 us per lookup) AGREE, fixed: the key is master's again (20,000 Map(Enum16(2000), Int64) serialization requests: 0.293 s master, 0.291 s now); the element serialization keys already determine the defaults
💡 The bulk fill is the same as createColumnWithDefaults in #130259 noted: no such helper on master; whichever PR merges second switches to it
💡 A missing Enum column is filled row by row noted: only the fill that stored an invalid value before; trivial types keep their code path

Round 2 (delta re-review of the fix): no findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local on master 1d4ff153: a Native file without status, read as status Enum8('a' = 1, 'b' = 2), gives [0,0]; JSONColumns {"id": [1, 2]} gives [0,0]; JSONEachRow {"t": {"n": 5}} into t Tuple(n UInt8, status Enum8(...)) gives 0; INSERT INTO events SELECT * FROM file('old.native') then SELECT * fails Code: 691 every time. Same on 26.3.33.24, 26.8.21.12, 26.10.2.103.
b Root cause explained? The three readers fill an absent value through the column API (cloneResized, insertManyDefaults, insertDefault), which knows only the column zero. The Enum default is its lowest member and only IDataType::insertDefaultInto knows it; AddingDefaultsTransform repairs only columns with a DEFAULT expression, so the 0 is stored.
c Fix matches root cause? Yes. The fill sites ask the type for its default when isDefaultInsertTrivial() is false (the HashJoinResult.cpp branch). SerializationTuple had no element types to ask, so it now holds them (not part of its pool key).
d Test intent preserved / new tests added? New 05628_missing_values_get_type_default: Native (two Enum shapes plus the MergeTree end-to-end insert), JSONColumns, JSONEachRow named Tuple ({}, Array(Tuple), nested Tuple), unchanged defaults for String / Array / Nullable(Enum) elements, and a missing Nothing element still accepted. No existing test changed.
e Both directions demonstrated? Pre-fix binary: 05628 fails with Code: 691 (runner and clickhouse local). Fixed binary: passes, 50/50 randomized runs (50 databases, 51 max_block_size, 7 session_timezone values), and 5x under ASan with no sanitizer report.
f Fix is general across code paths? Native, JSONColumns / JSONCompactColumns / JSONColumnsWithMetadata, and every JSON text format via SerializationTuple::deserializeTextJSON (JSONEachRow, JSONCompactEachRow, JSONObjectEachRow checked). JSONEachRow, TSKV, BSONEachRow missing columns already use insertDefaultInto. Parquet / ORC / Arrow / Vortex: #130259; CSV / TSV / *WithNames: #130975. The JSON type and JSONExtract keep the zero: their defaults decide Nullable(Tuple) NULLs and Variant alternatives, a separate change.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked: Enum8, Enum16 (lowest member -5 picked), Tuple(Enum) and nested Tuple, JSON(e Enum8) typed path, Array(Enum) [], Map(String, Enum) {}, Nullable(Enum) NULL, LowCardinality(Nullable(String)) NULL, UInt8 / String 0 / '', 1 and 2 rows. input_format_force_null_for_omitted_fields and input_format_json_defaults_for_missing_elements_in_named_tuple = 0 still raise their errors.
h Backward compatible? No setting and no format change. Only values that were outside the type's domain (or the wrong member) change; trivial types take their unchanged code path. Serialization pool keys are in-memory only.
i Invariants and contracts preserved? Each filled column gets exactly rows values (insertManyDefaultsInto / one insertDefaultInto per missing element), so block and tuple element sizes stay equal; addElementSafe still rolls back a failed row; block_missing_values bits unchanged. A pooled SerializationTuple is shared only by tuples whose element serializations have equal keys, which fixes every non-trivial default (Enum hashes its values; a JSON element is never pooled).

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

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e382c90]

Summary: ✅


AI Review

Summary

PR #131189 uses type defaults for columns missing from Native and JSONColumns input and named Tuple elements missing from JSON objects, preventing invalid or incorrect Enum values. Reviewed head e382c90bd2198285258519cdecbabadf2c222faa, the full diff, current callers and default implementations, serialization pooling, and all prior discussion. No actionable findings. The new 05628_missing_values_get_type_default regression test passes in Fast test.

Missing context / blind spots
  • ⚠️ Broader CI validation is incomplete: Finish Workflow reports that bugfix validation jobs were dropped following Config Workflow, leaving new_tests_check.py failing. Rerun the affected workflow to complete the required CI checks. Local tests were not run; runtime evidence comes from the focused CI result and the author's reported pre-fix, repeated, and ASan runs.
Final Verdict

✅ Approve — no actionable code findings. Required CI checks still need to complete successfully before merge.

@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-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/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 e382c90bd 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.78, programs/clickhouse-keeper ×0.64 (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.3 s 12.0 s +7.0 s (+142%)
Compile time of recompiled translation units

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

Job report

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 13, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai I am seeing lots of prs fixing default values for types today. Are you sure there is no design issue?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, there is one, and it is specific to Enum.

Enum8/Enum16 is the only type whose default, the lowest member (DataTypeEnum::insertDefaultInto), differs from the column zero (IColumn::insertDefault); Tuple and JSON only inherit it. The column is a plain ColumnVector<Int8/Int16> and cannot know its default, and the zero is also the value sparse serialization omits on disk, so the column zero cannot simply become the lowest member without misreading existing parts. Master's own comment there says IDataType::insertDefaultInto "breaks the abstraction of the separation of data types, serializations, and columns" (DataTypeEnum.cpp).

Measured on master 21809eaa:

  • A reader that fills a missing, NULL or DEFAULT value through the column stores 0. src/Formats, src/Processors/Formats and src/DataTypes/Serializations have 162 column-level fills and 10 type-level ones. For every type without an Enum inside the zero is the default, so only the Enum cases are bugs, and today's PRs are those cases. The nested Array/Map/Tuple paths (22 call sites) are still open: {"a":[null]} read as Array(Enum8('a' = 1, 'b' = 2)) gives [0].
  • Nothing downstream checks the domain. Text parsing and CAST reject a non-member, binary input and storage do not: INSERT INTO t SELECT * FROM format(RowBinary, 'e Enum8(''a'' = 1, ''b'' = 2)', unhex('0007')) stores [0, 7], then SELECT * FROM t fails with Code: 691. So every wrong fill ends as an unreadable table instead of an error.

Options:

  1. Put the default on the serialization. SerializationEnum already holds the Enum values (it validates text reads with them), the nested readers hold their element serializations, and the null_as_default helpers receive the nested one. A virtual "insert default" on ISerialization (column zero by default, lowest member for Enum, recursive for Array/Map/Tuple/Nullable) fixes every format reader without passing types into serializations. Passing types is what the per-site route needs, and it touches the serialization pool key: hashing element types there made each serialization lookup for system.metric_log's Map(Enum16, Int64) 51.9x slower, which this PR dropped before publishing.
  2. Check the domain on INSERT for columns that contain an Enum (other tables pay nothing). A wrong fill anywhere, now or later, becomes an INSERT error instead of a corrupt part. It also rejects raw out-of-domain binary input, which is a behaviour change.
  3. Keep fixing per site.

The open PRs fix bugs present in released versions, so I would keep them. I will hold the remaining per-site work (the nested paths) until you choose. Do you want me to do 1, with 2 as a separate PR, or do you prefer another direction?

Merged via the queue into ClickHouse:master with commit 544355c Nov 13, 2026
604 of 608 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
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-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/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.

3 participants