Skip to content

Cherry pick #112338 to 26.8: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column - #119803

Merged
robot-clickhouse merged 8 commits into
backport/26.8/112338from
cherrypick/26.8/112338
Sep 14, 2026
Merged

robot-clickhouse merged 8 commits into
backport/26.8/112338from
cherrypick/26.8/112338

Conversation

@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Original pull-request #112338

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 7 commits July 28, 2026 12:51
… column

Reading a subcolumn whose own type is Nullable or LowCardinality(Nullable) out
of a Variant, Dynamic or JSON column stored in a MergeTree table crashed the
server. Three lines of plain SQL with default settings are enough:

    CREATE TABLE m (id UInt64, value Dynamic) ENGINE = MergeTree ORDER BY id;
    INSERT INTO m VALUES (1, CAST(tuple(CAST(1, 'Nullable(UInt32)'), 's'),
                                 'Tuple(a Nullable(UInt32), b String)'));
    SELECT value.`Tuple(a Nullable(UInt32), b String)`.a FROM m;

On a debug build this is a LOGICAL_ERROR ("Bad cast from type
DB::DataTypeNumber<unsigned int> to DB::DataTypeNullable"); on a release build
assert_cast degrades to a plain static_cast, so it is a segfault. Reproduced on
26.7.2.26, 26.6.2.120, 26.5.6.78 and 26.3.17.78. The same query against
ENGINE = Memory returns the correct value.

SerializationVariantElement recurses into the serialization of the on-disk
element, and the extraction framework exposes such an element as Nullable(T)
even though it is stored non-nullable. To keep the type it hands down consistent
with that nested serialization, it stripped nullability unconditionally. That
strip cannot distinguish nullability added by the extraction from nullability
intrinsic to the requested subcolumn: for a Nullable tuple element the nested
serialization is a SerializationNullable, and the strip removes exactly the
nullability it requires.

Strip only when the extraction's wrap actually changed the type. The decision is
made where the wrap happens and passed down as an explicit flag, which is also
part of the serialization's pooling key so that two serializations differing only
in it cannot share a pooled instance.

Both methods that recurse into the nested serialization are gated: gating only
enumerateStreams would move the crash into deserializeBinaryBulkWithMultipleStreams
instead of removing it. On the gated deserialization path the element's own null
map is read by the nested serialization, and the NULLs of rows belonging to other
variants come from insertDefault/insertManyDefaults.

Dynamic computes the flag in DataTypeDynamic::getSubcolumnData against the type
before the wrap. Variant derives it inside VariantSubcolumnCreator::create, where
prev_type is the selected subcolumn's pre-wrap type; deciding it once per variant
alternative is not sufficient, because with
allow_nullable_tuple_in_extracted_subcolumns = 1 the alternative's own wrap does
change the type and the strip would still fire on the intrinsically nullable
element. The shared-variant branch keeps an unconditional strip: its column is
always Nullable over the shared variant type while its nested serialization is a
plain String serialization.

IDataType::getSubcolumnData now applies a creator to the serialization before the
type, matching ISerialization::createFromPath, so the Variant predicate sees a
pre-wrap prev_type on both read paths. This is a prerequisite of the fix and is
behaviour-neutral for every creator that ignores its prev_type argument.

No on-disk format change and no new or changed setting. Parts written before this
change are read correctly afterwards; before it they could not be read at all.
Three lines of the test read as coverage but would pass byte-identically with
the fix reverted, so the suite was weaker than the PR description.

The JSON coverage only requested a non-nullable typed path, whose nullability is
added by the extraction, i.e. the pre-existing always-correct path. A JSON object
value is decomposed into one dynamic path per leaf, so a nested tuple never
materialises as a single dynamic value and no untyped JSON path can carry the
bug. A typed path keeps its declared type intact, so a path declared as a Variant
whose alternative is the nullable-element tuple is the reachable route; it aborts
on unfixed master. The original non-nullable line is kept as a control.

The runner draws min_bytes_for_wide_part = 0 with about 30% probability, and only
the wide table pinned its part thresholds, so on such a run every table was wide
and the compact reader - the one whose stack produced the original report - was
not covered at all. All the other tables now pin compact thresholds explicitly,
so the split no longer depends on the draw.

The paired query meant to build both serializations in one pool requested a type
that was not an alternative of that column, so it silently took the shared
variant branch instead. An extra row makes the type a real alternative. The two
instances are still discriminated by their nested serialization, which no
reachable query can make agree, so the comment now says that rather than claiming
a pool collision the query cannot produce.

Co-Authored-By: Claude Fable 5 <[email protected]>
master rewrote SerializationVariantElement::deserializeBinaryBulkWithMultipleStreams
twice since the branch point ("Remove rows_offset from the deserialization API" and
"Deserialize columns into IColumn& to fix substreams-cache clone regression"): the
discriminators and variant columns no longer live in the deserialization state, and
the result column is an IColumn& instead of a ColumnPtr &.

Both guards this branch adds to that function are conditions on expressions master
rewrote, so master's body is kept and only the conditions carry the
nullable_added_by_extraction test:

* the null map fill and the descent into the nested column now guard master's
  isColumnNullable(result_column) / inner_column = &nullable_column.getNestedColumn();
* the LowCardinality(Nullable) strip now guards master's unconditional
  isColumnLowCardinalityNullable(*inner_column) on the fresh variant clone.

The hand resolution touches one file: the two conditions, removal of the enclosing
block master deleted, and one comment compressed from 5 lines to 3. enumerateStreams,
the getHash and create signatures, and VariantSubcolumnCreator::create merged
unchanged, as did the other five files.
Both conflicts came from master renaming the dynamic-subcolumn result structure
(`res->serialization`/`res->type` -> `res->data.*`, `dynamic_subcolumn_data` ->
`dynamic_subcolumn_info->data`). Resolved by keeping this branch's semantics in master's
spelling: the ordering in `DataTypeDynamic::getDynamicSubcolumnData` that computes
`nullable_added_by_extraction` across the type wrap, and the serialization-before-type
creator order in `IDataType::getSubcolumnData`. Master's own
`ISerialization::createFromPath` already applies the creator in that same order.

#116739 (`8f3f7df0d3150`) landed on master after this branch was last updated, adding
`wrapColumnForDeserialization` overrides to `SerializationVariantElement` and
`SerializationDynamicElement` that peel the result column's `Nullable` level whenever
`isColumnNullable`. This branch makes the matching unwrap in
`deserializeBinaryBulkWithMultipleStreams` conditional on `nullable_added_by_extraction`, so
the wrap was checked against that flag too. Gating it changes no observable behavior: for an
intrinsic `Nullable` the peel hands the nested column to a `SerializationNullable`, which
does not override `wrapColumnForDeserialization`, so rebuilding the `ColumnNullable` around
it reproduces the input layout. Measured on this tree, 04652, 04653 and 05045 all pass both
with the gate and without it. The overrides are therefore left byte-identical to master, and
only the comment that described the unwrap as unconditional is corrected.

Validation on the merged tree (debug, build id a395d5b3272a6dd9d33e1a4bf2ee5a9ab4766540):
04652, 04653 and master's own 05045 all pass. With the six `src/` files reverted to master
(build id ed053ed21015c958), 05045 still passes while 04652 and 04653 fail with
`Bad cast from type DB::DataTypeNumber<unsigned int> to DB::DataTypeNullable`, so the fix
this branch carries is still load-bearing and is not superseded by anything on master.

Co-Authored-By: Claude Opus 5 <[email protected]>
…-nullable-tuple-subcolumn

# Conflicts:
#	src/DataTypes/DataTypeDynamic.cpp
…-tuple-subcolumn

Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
@robot-ch-test-poll robot-ch-test-poll added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-critical-bugfix labels Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

I resolved the 26.8 conflicts of #112338 and validated the result. The last step needs someone with write access, so the resolution itself is below.

The cause is narrow: 26.8 does not carry master's SubcolumnInfo refactor, so 3 hunks in 2 files (DataTypeDynamic.cpp, IDataType.cpp) have to be re-expressed in this branch's vocabulary. The other 4 source files and both test files apply verbatim, and at this ref they are byte-identical to master before #112338, which is also the proof that 26.8 carries the defect.

Validated on the resolved tree: the official 26.8.4.2 binary segfaults on a 3-statement default-settings reproducer (rc=139, 3/3, SerializationNullable::enumerateStreams into IDataType::tryGetSubcolumnType), while the resolved build returns the correct value; 04652 and 04653 pass, 100/100 with settings randomization on. Forcing the ported nullability flag to false reddens both tests, so the adaptation is load-bearing rather than cosmetic. No master-side refactor is imported and 26.8's own submodule pins are kept.

To land it: merge backport/26.8/112338 into cherrypick/26.8/112338, resolve the two files as below, and push. That is a strict fast-forward of cherrypick/26.8/112338, so it cannot overwrite anyone's work, and it leaves the branch in the same two-parent shape the cherry-pick script builds itself, after which this PR stops conflicting and the automation finishes the chain on its own.

The 3 hunks, as a diff against backport/26.8/112338
diff --git a/src/DataTypes/DataTypeDynamic.cpp b/src/DataTypes/DataTypeDynamic.cpp
--- a/src/DataTypes/DataTypeDynamic.cpp
+++ b/src/DataTypes/DataTypeDynamic.cpp
@@ -987,16 +987,22 @@ std::unique_ptr<IDataType::SubstreamData> DataTypeDynamic::getDynamicSubcolumnDa
         }
     }
 
+    /// Make resulting subcolumn Nullable only if type subcolumn can be inside Nullable or can be LowCardinality(Nullable()).
+    bool make_subcolumn_nullable = canExtractedSubcolumnsBeInsideNullableOrLowCardinalityNullable(subcolumn_type);
+    auto subcolumn_type_before_wrap = res->type;
+    if (!is_null_map_subcolumn && make_subcolumn_nullable)
+        res->type = makeNullableOrLowCardinalityNullableSafe(res->type);
+    /// res->serialization serializes the type before the wrap above, so it must know whether the
+    /// nullability it will be handed at read time is that wrapper or the requested type's own.
+    bool nullable_added_by_extraction
+        = !isNullableOrLowCardinalityNullable(subcolumn_type_before_wrap) && isNullableOrLowCardinalityNullable(res->type);
     res->serialization = SerializationDynamicElement::create(
         res->serialization,
         dynamic_serialization.createSerializationForType(ColumnDynamic::getSharedVariantDataType()),
         subcolumn_type->getName(),
         String(subcolumn_nested_name),
-        is_null_map_subcolumn);
-    /// Make resulting subcolumn Nullable only if type subcolumn can be inside Nullable or can be LowCardinality(Nullable()).
-    bool make_subcolumn_nullable = canExtractedSubcolumnsBeInsideNullableOrLowCardinalityNullable(subcolumn_type);
-    if (!is_null_map_subcolumn && make_subcolumn_nullable)
-        res->type = makeNullableOrLowCardinalityNullableSafe(res->type);
+        is_null_map_subcolumn,
+        nullable_added_by_extraction);
 
     if (data.column)
     {
diff --git a/src/DataTypes/IDataType.cpp b/src/DataTypes/IDataType.cpp
--- a/src/DataTypes/IDataType.cpp
+++ b/src/DataTypes/IDataType.cpp
@@ -190,9 +190,12 @@ std::unique_ptr<IDataType::SubstreamData> IDataType::getSubcolumnData(
                         auto tmp_subpath = subpath;
                         if (tmp_subpath[i].creator)
                         {
+                            /// Build the serialization before the type is wrapped, so that a creator
+                            /// inspecting its prev_type argument sees the type the serialization
+                            /// actually serializes. Same order as in ISerialization::createFromPath.
+                            dynamic_subcolumn_data->serialization = tmp_subpath[i].creator->create(dynamic_subcolumn_data->serialization, dynamic_subcolumn_data->type);
                             dynamic_subcolumn_data->type = tmp_subpath[i].creator->create(dynamic_subcolumn_data->type);
                             dynamic_subcolumn_data->column = tmp_subpath[i].creator->create(dynamic_subcolumn_data->column);
-                            dynamic_subcolumn_data->serialization = tmp_subpath[i].creator->create(dynamic_subcolumn_data->serialization, dynamic_subcolumn_data->type);
                         }
 
                         tmp_subpath[i].data = *dynamic_subcolumn_data;

Resolve the two conflicts in `DataTypeDynamic.cpp` and `IDataType.cpp`: 26.8 does not carry
master's `SubcolumnInfo` refactor, so the PR's hunks are re-expressed on `SubstreamData`
(`res->type` / `res->serialization` / `dynamic_subcolumn_data`), following the resolution
proposed by groeneai in #119803 (comment).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks, @groeneai. I merged backport/26.8/112338 into cherrypick/26.8/112338 and resolved DataTypeDynamic.cpp and IDataType.cpp exactly as in your diff (the only two conflicting files; the other 8 files applied verbatim). Pushed as c37b938, a fast-forward of the branch. The four affected translation units (DataTypeDynamic.cpp, IDataType.cpp, SerializationDynamicElement.cpp, SerializationVariantElement.cpp) compile on the 26.8 tree. The robot should now finish the chain on its own.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! pr-critical-bugfix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants