Repository navigation
Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column - #112338
Conversation
… 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]>
Internal second-model review (2 rounds, 9 findings adjudicated) - click to expandBefore opening this PR I ran two independent review rounds against the diff: a cold Round 1 - 4 findings, all accepted and fixedAll four were in the test suite, and all four were the same class: something the PR claims
The fixes: the All seven tables now pin both The pooling case is now genuinely reached (an added row makes the nullable tuple a real Round 1 found no defect in the Round 2 - 4 findings,
|
| Finding | Verdict | |
|---|---|---|
| ❌ | The changelog entry nested a backslash-escaped backtick pair inside a single-backtick code span. Backslash escapes are not processed inside code spans, so the span closed early and the entry would have rendered as a truncated fragment plus a dangling backtick, in CHANGELOG.md. |
AGREE. Fixed with a double-backtick span |
| The description asserted the pooling-key change as a necessity, while the implementation had measured the opposite and softened the in-code comment accordingly. Leaving the two inconsistent on the same page. | AGREE. Description now matches | |
The description named JSON without naming the route, which is the part that makes the claim checkable. |
AGREE. Route now stated | |
| 💡 | The getHash field has no live test. |
DISAGREE. Unreachable by construction: covering it needs two requests identical in nested serialization, element name, discriminator and variant count but differing in the flag, and the flag is a deterministic function of the same pre-wrap type that selects the nested serialization. Correct as a pooling-key invariant, now honestly described. |
Round 2's second-model pass returned zero findings after reading all changed files and
tests in full and tracing the Variant/Dynamic/JSON/Nullable/LowCardinality/shared-data
siblings.
Verified independently rather than accepted
prev_type == nullptrfails the new predicate closed (do not strip). I traced whether a
null type can reach a read: the type-less path is the part's own serialization map, whose
consumers are stream-name and kind-stack only; the reader builds its serializations through
getSubcolumnSerialization, which always passes a type. The flag affects only the recursion
payload and the read path, never a stream name.- Every caller of the four changed signatures, repo-wide. Both
createoverloads lost their
default arguments, so an omitted flag is a compile error rather than a silentfalse. - The behaviour-neutrality argument for the creator-order change, against
hasSubcolumnForPath's accepted substream types and all ten creator-attachment sites. - That a row of another variant still reads as
NULLon the gated paths, via
ColumnNullable::insertDefaultandColumnLowCardinality::insertDefaultresolving to the
dictionary's null index. - That the pinned thresholds keep
canUsePolymorphicPartstrue, so no warning is logged.
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-45:20260728-155800 |
|
cc @Avogar @KochetovNicolai - could you review this? |
|
Workflow [PR], commit [20f4427] Summary: ✅
AI ReviewSummaryThis PR fixes the Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 20f4427.
Changed lines: Changed C/C++ lines covered: 92/92 (100.00%) · Uncovered code |
CI finish ledger - 6d6f615Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
The diff here is 6 One note on the MySQL 8 line: #96252 is the only Session id: cron:our-pr-ci-monitor:20260728-223000 |
|
cc @Avogar |
|
Fixing PR for the Root cause is in the MySQL 8 test image, not in this pull request: the container's entrypoint runs |
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units18 translation units recompiled, 52 s compile time in total, 18 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.10 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
|
Fixing PR for the |
CI finish ledger - d5ac8d5Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
CI is fully finished at this head: 175 unique check runs, 0 incomplete, one parent workflow run Neither red is caused by this PR, and both were measured rather than assumed. STID 3227-52fd was settled with a 4-arm matrix against a master snapshot proven to lack this fix: STID 1559-1b3e was reproduced on the same master snapshot with none of this PR's changes present SET enable_nullable_tuple_type = 1;
CREATE TABLE probe (`key` Int128, `t` Tuple(m Map(LowCardinality(String), Decimal(76, 11))) NULL)
ENGINE = MergeTree ORDER BY key SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO probe SELECT number, tuple(map(concat('k', toString(number % 4)), number)) FROM numbers(1000);
SELECT count(), singleValueOrNull(t.m['%']) FROM probe;The fuzzer reached it by mutating Session id: cron:our-pr-ci-monitor:20260827-190000 |
|
Fixing PR for the The cause is Minimal repro on master, no fuzzer, none of this PR's files, and none of the fuzzed fixture's map or serialization settings: SET enable_nullable_tuple_type = 1;
CREATE TABLE f (key Int64, t Tuple(m Map(String, UInt64)) NULL)
ENGINE = MergeTree ORDER BY key SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO f SELECT number, tuple(map('k', number)) FROM numbers(10);
SELECT singleValueOrNull(t.m['k']) FROM f;With Measured on the shared master debug snapshot |
|
Dear @Avogar, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
6214c60
Cherry pick #112338 to 26.8: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
…mn of a Variant or Dynamic column
…column crash
Reading a subcolumn whose own type is Nullable out of a Variant or Dynamic column
segfaults on 26.7: SerializationVariantElement could not tell a Nullable level that
subcolumn extraction had added (whose null map it must fill from the discriminators
and peel off before recursing) from a Nullable level intrinsic to the requested type
(which belongs to nested_serialization), so it stripped the latter and handed the
nested serialization a column shape it does not read.
The robot cherry-pick conflicts because 26.7 predates two master refactors. Neither is
imported here; the fix is re-expressed in 26.7's own naming.
Axis A, the SubcolumnInfo refactor is master-only:
- res->data.{type,serialization} spelled res->{type,serialization};
- dynamic_subcolumn_info->data.X spelled dynamic_subcolumn_data->X;
- nested_name_to_store (a separate master PR's zero-array-level renaming) spelled
with the branch's inline String(subcolumn_nested_name).
Axis B, deserializeBinaryBulkWithMultipleStreams still has the older
(ColumnPtr & result_column, size_t rows_offset, ...) signature with the
mutable_column idiom and a persisted variant_element_state->variant. The branch's two
conditions are kept line for line and only gated with nullable_added_by_extraction,
which is semantically identical to master's inner_column form: when the flag is false
both trees leave the still-Nullable column with nested_serialization, and the later
insertManyDefaults/insertRangeFrom/insertFrom calls operate on the same column level.
wrapColumnForDeserialization does not exist on 26.7 (zero hits in the .cpp and the .h),
and #112338's only change to it was replacing three comment lines with three others, so
that hunk is dropped: no semantics are lost and no absent symbol is referenced. The
serialization pool does exist here, so the getHash update that threads the new flag
into the pooling key is kept, otherwise two serializations differing only in the flag
would collide.
Validated on this branch: the three-line reproducer segfaults on the official
26.7.8.5 build (rc=139, 3/3) and returns 1 here; 04652 and 04653 pass, both .reference
files byte-identical to master's blobs; forcing the flag to a constant false or true
reddens 04652 in either direction.
Related: #112338
Related: #119802
Cherry pick #112338 to 26.7: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
…mn of a Variant or Dynamic column
Cherry pick #112338 to 26.3: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
…mn of a Variant or Dynamic column
Cherry pick #112338 to 26.6: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
…mn of a Variant or Dynamic column
Backport #112338 to 26.8: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
Backport #112338 to 26.6: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
Backport #112338 to 26.7: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
Backport #112338 to 26.3: Fix a crash when reading a nullable subcolumn of a Variant or Dynamic column
|
@groeneai @Avogar @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
…criminators
For a Variant/Dynamic/JSON element that is a tuple, the null map of a Nullable
field of that element returned 0 on every row holding a different alternative,
although the field itself reads NULL there. Since optimize_functions_to_subcolumns
is enabled by default and rewrites isNull(x) to x.null, a plain
SELECT count() FROM t WHERE value.`Tuple(a Nullable(UInt32), b String)`.a IS NULL
silently dropped the matching rows: 1 instead of 2 on a three-row merged part.
SerializationVariantElement fills rows whose discriminator is not the element's
with the result column's default. For the value read that default IS NULL, so it
is correct; a null map is a bare UInt8 whose default 0 means "not null", which
makes it the one subcolumn whose value for an absent element is not its default.
Nothing on the path could distinguish the two: SerializationVariant::enumerate
Streams attaches one subcolumn creator per alternative, while the selection
happens per subcolumn beneath it, and ISerialization::createFromPath hands a
creator only the selected subcolumn's (serialization, type, column) - where a
null map's type is plain UInt8, indistinguishable from a genuine UInt8 element.
prev_type, which ClickHouse#112338 used to derive nullable_added_by_extraction, therefore
carries one bit too few for this case.
So ISubcolumnCreator gains one virtual with a default no-op,
specializeForSelectedSubcolumn, which names the selected substream to the
enclosing creators. VariantSubcolumnCreator uses it to learn that the selection
is a null map and then writes 1 for absent rows at all four read sites and in
both in-memory creator paths. SerializationVariantElementNullMap already does
exactly this for the top-level x.<Elem>.null, and cannot serve the nested case
because all three of its create() overloads discard prev and would throw away
the field's own on-disk null map. Nine of the ten creators inherit the no-op.
createFromPath and makeSubcolumnInfo also pass the true selected terminal, since
on the dynamically-resolved-descendant arm the leaf lives in the nested path and
path[prefix_len - 1] is only the prefix the dynamic type matched.
Two guards keep the change to the case where the null map is the only place the
information can live: the extraction must not have wrapped the element in
Nullable, where absence is already NULL, and the selection must still be a bare
UInt8, since an Array or Map below has already made it Array(UInt8), whose value
for an absent element is the correct default []. That leaves the fix orthogonal
to ClickHouse#119222, which flips allow_nullable_tuple_in_extracted_subcolumns to true.
No on-disk or format change: the same streams are requested and only the value
written into rows where the element is absent changes. This is not a regression -
released 26.8.3.105 already returns 0 there; our ClickHouse#112338 removed a SIGSEGV on the
sibling value read, which is what makes the contradiction observable and puts the
IS NULL rewrite on a completing path.
Closes: ClickHouse#119935
Co-Authored-By: Claude Opus 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a crash when reading a subcolumn of a
Variant,DynamicorJSONcolumn whose own type isNullableorLowCardinality(Nullable)from aMergeTreetable, for exampleSELECT value.`Tuple(a Nullable(UInt32), b String)`.aover aDynamiccolumn. Previously such a read hit aLOGICAL_ERRORin debug builds and crashed in release builds.Description
No related open issue found (searched open issues and PRs for the crash message, the stack frames and the affected functions).
Three lines of plain SQL with default settings crash the server:
On master (debug) this is
Logical error: 'Bad cast from type DB::DataTypeNumber<unsigned int> to DB::DataTypeNullable'; on 26.7.2.26, 26.6.2.120, 26.5.6.78 and 26.3.17.78 it is a segfault, because in a release buildassert_castdegrades to a plainstatic_cast. The same query againstENGINE = Memoryreturns the correct value.SerializationVariantElementrecurses into the serialization of the on-disk element, and the extraction framework exposes such an element to the user asNullable(T)even though it is stored non-nullable (DataTypeDynamic::getDynamicSubcolumnInfo,VariantSubcolumnCreator::create). To keep the type it hands down consistent with that nested serialization,SerializationVariantElementunconditionally stripped nullability off the type and the column.That strip cannot tell nullability that the extraction added from nullability intrinsic to the requested subcolumn. When the requested subcolumn is a tuple element that is itself
Nullable, the nested serialization is aSerializationNullableand the strip removes exactly the nullability it requires:SerializationNullable::enumerateStreamsthen casts aUInt32type toDataTypeNullable, anddeserializeBinaryBulkWithMultipleStreamscasts aColumnUInt32toColumnNullable.The fix records at the site that performs the wrap whether the wrap actually changed the type, and strips only then. The flag is also part of the serialization's pooling key, so that two serializations differing only in it can never share a pooled instance. That is defence in depth rather than a fix for a reachable case: the two are already distinguished by their nested serialization, and dropping the flag from
getHashleaves the tests green.SerializationVariantElementgainsnullable_added_by_extraction, which gates the strip inenumerateStreamsand both unwraps indeserializeBinaryBulkWithMultipleStreams. Gating only the first would move the crash into deserialization instead of removing it. On the gated path the element's own null map is read by the nested serialization, and the NULLs for rows belonging to other variants come frominsertDefault/insertManyDefaults.Dynamiccomputes the flag inDataTypeDynamic::getDynamicSubcolumnInfoagainst the type before the wrap and forwards it throughSerializationDynamicElement.Variantderives it insideVariantSubcolumnCreator::create(prev, prev_type), whereprev_typeis the selected subcolumn's pre-wrap type. Deciding it once per variant alternative instead is not sufficient: withallow_nullable_tuple_in_extracted_subcolumns = 1the alternative's own wrap does change the type, so the strip would still fire on the intrinsically nullable element and theVariantcase would keep crashing.SerializationDynamicElementkeeps an unconditional strip. Its column is alwaysNullableover the shared variant type while its nested serialization is a plainStringserialization, so forwarding the flag there would break a case that works today.IDataType::getSubcolumnInfonow applies a creator to the serialization before the type, so that a creator reading itsprev_typeargument sees the type itsprevserialization actually serializes.ISerialization::createFromPathalready had that order; this branch was the only place with the other one, which madeprev_typemean "pre-wrap" on one path and "post-wrap" on the other. It is behaviour-neutral: the creator here istmp_subpath[i].creatorfor anithat satisfieshasSubcolumnForPath, and of the creator-attachment sites insrc/onlySerializationNamed(for aTupleElementsubstream) andSerializationSparse(forSparseNullMap) attach to a substream type that predicate accepts - both take an unnamed second parameter and ignore it. It is in this PR because the two orders disagreeing is what would make theVariantpredicate's meaning depend on which path resolved the subcolumn, not because anything reachable today changes.Covered by
04652_nullable_tuple_element_subcolumn_of_dynamic_variant(Variant,Dynamic,LowCardinality(Nullable), a nested tuple element, an unnamed tuple element, wide and compact parts,PREWHERE, an aggregate, the null-map subcolumn, mixed rows against aMemoryoracle, plus the controls that must keep working - above all a non-nullable top-level element, whose nullability really is added by the extraction) and by04653_nullable_tuple_element_subcolumn_nullable_tuple_settingforallow_nullable_tuple_in_extracted_subcolumns = 1, which is read from the global context and so needs a command-line setting.JSONreaches the same extraction through a typed path whose type is aVariant, so the covering case isJSON(t Variant(Tuple(a Nullable(UInt32), b String), String)). A dynamic path is not affected: an untyped object value is decomposed into one dynamic path per leaf, so a nested tuple never becomes a single dynamic value there. The test keeps a dynamic-path read as a control for the same route.The part thresholds are pinned per table in the test so that the compact and wide readers, which resolve the subcolumn through different code, are both covered on every run rather than depending on what the runner randomizes.
No on-disk format change, no new or changed setting, so no
SettingsChangesHistory.cppentry. Parts written before this change are read correctly afterwards; before it they could not be read at all.Workflow [PR]
Sync PR [sync-upstream/pr/112338]
Version info
26.9.1.1392(included in26.9and later)26.8.4.7,26.7.8.14,26.6.6.15,26.3.33.75